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
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>
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.
- Validate and Save your Ruby in TextMate – with secret Rubinus superpowers In some TextMate bundles, if you save a file it...
- Future proofing your Ruby code. Ruby 1.9.1 is coming. Bugger. I’m a Ruby monogamist. I use the Ruby...
- Unit Testing iPhone apps with Ruby: rbiphonetest Everything to love about Ruby: the concise, powerful language;...
- Using Ruby within TextMate snippets and commands I didn’t know you could run Ruby within TextMate snippets....
- Everything you wanted to know about Ruby.NET Recently Wayne Kelly spoke at the Brisbane Ruby and Rails...