2013-05-08 69 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