Ruby: Understanding the _why cloaker Method

I am trying to understand the _why cloaker method that he wrote about in the block costume :

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

I understand that class << self; self; end class << self; self; end class << self; self; end opens Eigenclass self , but I have never seen anyone do this inside an instance method before. What is self at the point where we do it? I was impressed with self to be the receiver that called the method, 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 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 if we open the Eignenclass of the HTML class or do it in a specific instance of the HTML class?

+7
source share
1 answer

Inside the cloaker method cloaker self will be an instance of HTML, since you name it on an object, so you effectively create a Singleton method for instances of the HTML class. For example:

 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, only the pre-1.9 method of calling "Object#define_singleton_method"

+1
source

All Articles