Access Ruby 'self' methods inside 'class << self' method definitions

99 views Asked by At

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 because Foo.superclass is just Object.
  • 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.

1

There are 1 answers

1
AudioBubble On

At the end of the video, we are offered several answers to this question.

First, something pretty ugly. You can reopen the class:

class Foo
  class << self
    baz
  end
end

And another way. Since class definitions are executed, you can return the inner self into a variable:

meta = class Foo
  class << self
    def self.baz
      puts "inside anonymous superclass method"
    end
    self # return self here
  end
end

meta.baz

Or, most elegantly you can open Class and add a method to it:

class Class
  def meta
    class << self
      self
    end
  end
end

# class Foo ...

Foo.meta.baz

which turns out to be just a reimplementation of Object#singleton_class.