I'm looking for a way (library or metaprogramming trick) to hook into method definition, so that I could extend certain classes and catch their method (re)definition "ev开发者_开发技巧ents".
There's the method_added callback (see http://www.ruby-doc.org/core/classes/Module.html#M001662 unfortunately, there is no documentation). You use it as follows:
class Foo
# define the callback...
def self.method_added(method_name)
puts "I now have a method called #{method_name}"
end
# the callback is called on normal method definitions
def foo
# "I now have a method called foo" will be printed
end
# the callback is called on method definitions using define_method
define_method :bar do
# "I now have a method called bar" will be printed
end
# the callback is called on method definitions using alias and the likes
alias :baz :foo # "I now have a method called baz" will be printed
end
Have you tried overriding "define_method" ? At least you could catch some of the "runtime" method definitions ?
Override method_added
. Keep in mind, though, that if you're dynamically modifying methods in method_added
, those will cause method_added
to be called as well, so you need to have some way of knowing which methods you're concerned with in order to avoid infinite recursion.
精彩评论