问题描述
我想制作一个钩子方法,该方法在每次调用类的任何函数时都会被调用.我已经尝试过method_added,但是它在类定义时仅执行一次,
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,
class Base
def self.method_added(name)
p "#{name.to_s.capitalize} Method's been called!!"
end
def a
p "a called."
end
def b
p "b called."
end
end
t1 = Base.new
t1.a
t1.b
t1.a
t1.b
Output:
"A Method's been called!!"
"B Method's been called!!"
"a called."
"b called."
"a called."
"b called."
但是我的要求是,在程序中任何地方调用的类的任何函数都将触发"method_ named"钩子方法.
but my requirement is that any function of a class that gets called anywhere in the program triggers the "method_called", hook method.
Expected Output:
"A Method's been called!!"
"a called."
"B Method's been called!!"
"b called."
"A Method's been called!!"
"a called."
"B Method's been called!!"
"b called."
如果有已定义的现有钩子方法可以正常工作,请进行介绍.
If there is any defined existing hook method that works just the same, then please tell about it.
先谢谢了.
推荐答案
看看 Kernel#set_trace_func
.它使您可以指定在事件(例如方法调用)发生时将调用的proc.这是一个示例:
Take a look at Kernel#set_trace_func
. It lets you specify a proc which is invoked whenever an event (such as a method call) occurs. Here's an example:
class Base
def a
puts "in method a"
end
def b
puts "in method b"
end
end
set_trace_func proc { |event, file, line, id, binding, classname|
# only interested in events of type 'call' (Ruby method calls)
# see the docs for set_trace_func for other supported event types
puts "#{classname} #{id} called" if event == 'call'
}
b = Base.new
b.a
b.b
输出:
Base a called
in method a
Base b called
in method b
这篇关于定义"method_Called".如何创建每次调用类的任何函数时都会被调用的hook方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!