我想寫一點「棄用它」庫,並使用「method_added」回調很多。 但現在我注意到,當包含一個模塊時,這個回調沒有被觸發。紅寶石method_added回調不觸發,包括模塊
有沒有任何回調或變通方法,當somewhing被包含到自身中時,通知類「Foobar」?
小的演示證明:
# Including Moduls won't trigger method_added callback
module InvisibleMethod
def invisible
"You won't get a callback from me"
end
end
class Foobar
def self.method_added(m)
puts "InstanceMethod: '#{m}' added to '#{self}'"
end
def visible
"You will get a callback from me"
end
include InvisibleMethod
end
[:invisible, :visible, :wont_exist].each do |meth|
puts "#{meth}: #{Foobar.public_method_defined? meth}"
end
這就是結果:
InstanceMethod: 'visible' added to 'Foobar'
invisible: true
visible: true
wont_exist: false
附加信息:
我真的需要使用一個鉤狀method_added。
ActiveModel在運行時通過匿名模塊將public_instance_methods添加到類。
不幸的是我不認爲有一個很好的答案,但這可能會指向你的一些黑客工作的方向.. http:// stackoverflow。com/questions/4191214/callback-for-classes-defined-within-a-module – David 2012-02-21 23:45:53