2013-05-08 5 views
7

理解_whyのcloaker方法:ルビー:私は彼が「<a href="http://viewsourcecode.org/why/redhanded/inspect/aBlockCostume.html" rel="nofollow">A Block Costume</a>」に書いた_whyの<code>cloaker</code>方法を理解しようとしている

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

私はclass << self; self; endselfのEigenclassを開くことを認識し、私は決してきません前に誰かがインスタンスメソッドの中でこれを行うのを見た。 selfはこれを行う時点で何ですか?

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

だから何がmethod_missingコール内部selfです:メソッドがコールされたが、cloakermethod_missing内部から呼び出されたことを受信する必要があります私は印象self下にありましたか? cloakerメソッド内

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

:そして、我々が呼ぶときself何ですか?

基本的には、私たちがHTMLクラスのEignenクラスを開いているのか、それともHTMLクラスの特定のインスタンスに対して行っているのかを知りたいですか?

+2

のちょうど前の1.9の方法私はあなたの質問を理解していればわかりません。 'method_missing'はインスタンスメソッドなので、' self'は特定のインスタンスを参照し、 'class << self;自己; end'はそのインスタンスのEigenclassを返します。 – Stefan

+0

公式の用語は 'singleton_class'です –

答えて

1

メソッド内では、selfはHTMLのインスタンスになります。これはオブジェクトで呼び出すため、HTMLクラスインスタンスで効果的にシングルトンメソッドを作成しているからです。例えば:

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ミッタークはコメントとして、呼び出し"Object#define_singleton_method"

+3

もちろん、Ruby 1.9では、それは基本的に' def cloaker(&blk)define_singleton_method(:new_method、&blk)end'です。 –

関連する問題

 関連する問題