The explicit Ruby metaclass you know you always wanted

Posted by Dr Nic on April 03, 2008 and blessed with 5 comments

When you define a “static” or “class” method on a Ruby class, it actually stores the method on that class’s metaclass/singleton class/eigenclass.

_why’s metaid gem gives you a metaclass method to explicit access this object:

require 'metaid'
class Person
  def self.oldest
    # find oldest person
  end
end
Person.methods.grep(/oldest/) # => ['oldest']
Person.metaclass.instance_methods.grep(/oldest/) # => ['oldest']

So now here’s a new, fun way to access the metaclass of a class, look for a constant suffixed with ‘Metaclass’. For the Person class, look for PersonMetaclass. Yep, we can have explicit metaclass constants. Or try PersonClass or PersonEigen or PersonEigenclass. No one can agree on what they are called, so I made them all work.

$ gem install magic_metaclass
$ irb

In irb try:

require 'rubygems'
require 'magic_metaclass'
class Person; end
Person
# => Person
PersonMetaclass
# => #<Class:Person>
PersonClass
# => #<Class:Person>
PersonEigenclass
# => #<Class:Person>
PersonEigen
# => #<Class:Person>

Neat.

Finally, the example from above:

class Person
  def self.oldest
    # find oldest person
  end
end
PersonMetaclass.instance_methods.grep(/oldest/) # => ['oldest']

I wrote this gem with no known use cases. If you find any, let me know.

Related posts:

  1. Future proofing your Ruby code. Ruby 1.9.1 is coming. Bugger. I’m a Ruby monogamist. I use the Ruby...
  2. Unit Testing iPhone apps with Ruby: rbiphonetest Everything to love about Ruby: the concise, powerful language;...
  3. Using Ruby within TextMate snippets and commands I didn’t know you could run Ruby within TextMate snippets....
  4. Everything you wanted to know about Ruby.NET Recently Wayne Kelly spoke at the Brisbane Ruby and Rails...
  5. Ruby.NET goes Open Source … too late? Once upon a time there were two Ruby on .NET...
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Dr Nic Fri, 04 Apr 2008 02:04:50 UTC

    Ooh, I should add “PersonSingleton” too.

  2. el raichu Mon, 19 May 2008 12:23:34 UTC

    I wonder if there’s a PersonEigenEigen? Or a PersonEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigenEigen?

  3. Dr Nic Mon, 19 May 2008 12:25:49 UTC

    @el raichu [via] – there definitely is :)

  4. TJ Holowaychuk Mon, 22 Dec 2008 04:17:15 UTC

    haha I still have a hard time understanding why you would ever need to go any more than one level deep. I have a hard time even really understanding good use-cases for a metaclass method in the first place really (whys writing style just complicates things)

  5. Dr Nic Mon, 22 Dec 2008 07:50:47 UTC

    @TJ – you probably wouldn’t have more than one level. Ever.

Comments