2013-12-23 23 views
-1

我想計算在類中定義的新方法的方法調用。爲此,我使用method_added掛鉤重新定義每個新定義的方法。在裏面,我使用define_method and increment the value of a class variable @@ test_count`。在self.method_added中設置define_method的類變量

基類:

class Unit 
    @new_method = true 
    @@test_count = 0 

    def self.test_count 
    puts @@test_count 
    end 

    def self.method_added(name) 
    old_method = instance_method(name) 
    if @new_method 
     @new_method = false 
     define_method(name) do |*args, &block| 
     @@test_count += 1 
     old_method.call(*args, &block) 
     end 
     @new_method = true 
    end 
    end 
end 

子類與新定義的方法:

class Test < Unit 
    def test_assertion 
    puts true 
    end 
end 

當我打電話的新方法,@@test_count仍然是0:

Test.new.test_assertion 
Unit.test_count 

true 
0 

爲什麼@@test_count值ISN沒有改變?

+2

這是什麼@new_method?似乎沒有設置,因此無或錯所以一切都沒有得到執行。 – engineersmnky

+0

此外,使用此代碼,您的問題不可重現,您忘記了包含方法'instance_method'。 –

+0

我想'@ new_method'應該從開頭就設置爲'true',因爲這樣可以在'method_added'內添加新的方法,而不必進行無限遞歸。 'instance_method'來自'Module'類,它返回一個未綁定的實例方法http://ruby-doc.org/core-1.9.3/Module.html#method-i-instance_method。 – paradoja

回答

-1

該問題是由類0123¾的主體中初始化類實例變量@new_method造成的。由於我用Test對此類進行了子類化,因此此變量未在子類Test中初始化。沒有想法,爲什麼它是這樣的,但我這樣,通過nil從初始化的變量要通過檢查,然後分配合適的值給它改變ifunless解決了這個問題:

class Unit 
    @@test_count = 0 

    def self.method_added(name) 
    unless @new_method 
     @new_method = true 
     old_method = instance_method(name) 
     define_method(name) do |*args, &block| 
     @@test_count += 1 
     old_method.bind(self).call(*args, &block) 
     end 
     @new_method = false 
    end 
    end 
end 

任何想法,爲什麼類實例變量的初始化ISN」 t「繼承」在一個子類?

+0

解釋爲什麼downvote? – leemour