Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Understanding _why's cloaker method

Tags:

ruby

I'm trying to understand _why's cloaker method which he wrote about in "A Block Costume":

class HTML
  def cloaker &blk
    (class << self; self; end).class_eval do
      # ... rest of method
    end
  end
end

I realise that class << self; self; end opens up the Eigenclass of self, but I've never seen anyone do this inside an instance method before. What is self at the point where we do this? I was under the impression self should be the receiver that the method was called on, but cloaker is called from inside method_missing:

def method_missing tag, text = nil, &blk
  # ...
  if blk
    cloaker(&blk).bind(self).call
  end
  # ...
end

So what is self inside the method_missing call? And what is self when we call:

((class << self; self; end).class_eval)

inside the cloaker method?

Basically, I want to know whether we are we opening the Eignenclass of the HTML class, or if we are doing it to a specific instance of the HTML class?

like image 569
stephenmurdoch Avatar asked May 08 '13 13:05

stephenmurdoch


1 Answers

Inside the cloaker method, self will be an instance of HTML since you'll call that on a object, so you're effectively creating a Singleton Method on HTML class instances. For instance:

class HTML
  def cloaker &blk
    (class << self; self; end).class_eval do
      def new_method
      end
    end
  end
end

obj = HTML.new
obj.cloaker
p HTML.methods.grep /new_method/  # []
p obj.singleton_methods # [:new_method]

Edit

Or as Jörg W Mittag commented , just a pre-1.9 way of the calling "Object#define_singleton_method"

like image 112
fmendez Avatar answered Nov 13 '22 12:11

fmendez