While watching this video I came across an interesting question posed by the presenter, Dave Thomas. He is talking about the syntax we see all the time in Ruby class method definitions:
class Foo
class << self
def bar
puts "inside class method"
end
def self.baz
puts "inside anonymous superclass method"
end
end
end
Of course, we can access Foo.bar, but how does one go about baz? Dave Thomas talks about the class << self syntax inserting an anonymous superclass into the hierarchy. I tried the following:
- Calling
Foo.superclass.bazdoesn't work becauseFoo.superclassis justObject. - I poked around the available methods of the ancestry hierarchy to no avail.
Test.class_eval 'self.self.baz'...now things are getting a little ridiculous.
Thoughts?
The problem is presented around 44:23 in the video.
At the end of the video, we are offered several answers to this question.
First, something pretty ugly. You can reopen the class:
And another way. Since class definitions are executed, you can return the inner
selfinto a variable:Or, most elegantly you can open
Classand add a method to it:which turns out to be just a reimplementation of
Object#singleton_class.