2013-05-08 79 views
7

我想了解_why的cloaker方法,這是他在「A Block Costume」寫道:紅寶石:瞭解_why的cloaker方法

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

我意識到class << self; self; end開闢了self的Eigenclass,但我從來沒有以前任何人在一個實例方法中都會這樣做。什麼是self在我們這樣做的地步?我的印象是self應該是接收器,該方法被調用於下,但cloaker從內部method_missing稱爲:

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

那麼,什麼是selfmethod_missing調用之內?什麼是self當我們致電:

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

cloaker方法裏面?

基本上,我想知道我們是否我們打開HTML類的Eignenclass,或者如果我們將它做的HTML類的特定實例?

+2

方式不知道如果我明白你的問題。 'method_missing'是一個實例方法,所以'self'指的是特定的實例和'class << self;自; end'返回該實例的Eigen類。 – Stefan 2013-05-08 13:45:49

+0

注意,官方用語是'singleton_class' – 2013-05-08 16:26:22

回答

1

cloaker方法中,self將是HTML的一個實例,因爲您將在對象上調用該方法,所以您將有效地在HTML類實例上創建Singleton方法。例如:

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] 

編輯

或者作爲約爾格W¯¯米塔格評論,只是一個預1.9的調用"Object#define_singleton_method"

+3

當然,像Ruby 1.9的,這基本上只是'高清cloaker(BLK)define_singleton_method(:NEW_METHOD,與BLK)end' – 2013-05-08 14:12:40