我想計算在類中定義的新方法的方法調用。爲此,我使用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沒有改變?
這是什麼@new_method?似乎沒有設置,因此無或錯所以一切都沒有得到執行。 – engineersmnky
此外,使用此代碼,您的問題不可重現,您忘記了包含方法'instance_method'。 –
我想'@ new_method'應該從開頭就設置爲'true',因爲這樣可以在'method_added'內添加新的方法,而不必進行無限遞歸。 'instance_method'來自'Module'類,它返回一個未綁定的實例方法http://ruby-doc.org/core-1.9.3/Module.html#method-i-instance_method。 – paradoja