Defining “method_called”.. How do I make a hook method which gets called every t
原文来自:?http://stackoverflow.com/questions/3236194/defining-method-called-how-do-i-make-a-hook-method-which-gets-called-every-t
?
I want to make a hook method which gets called everytime any function of a class gets called. I have tried method_added, but it executes only once at the time of class definition,
?
?
?Outputs:
class Base def self.method_added(name) if /hook/.match(name.to_s) or method_defined?("#{name}_without_hook") return end hook = "def #{name}_hook\n p 'Method #{name} has been called'\n #{name}_without_hook\nend" self.class_eval(hook) a1 = "alias #{name}_without_hook #{name}" self.class_eval(a1) a2 = "alias #{name} #{name}_hook" self.class_eval(a2) end def a p "a called." end def b p "b called." endendt1 = Base.newt1.at1.bt1.at1.b?