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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With