4

I know that I can capture the moment of a method definition by using set_trace_func.

set_trace_func ->event, file, line, method, binding, klass{
  if event == "c-call" and method == :method_added
    # The moment of method definition
  end
}
  1. Is it possible to capture the name of the method being defined at such moment? I know that the class can be captured by eval("self", binding). What code can I put inside the block shown above to capture the method name?
  2. Is it further possible to get the format of the arguments for the method being defined (the required arguments, the rest of the arguments, and their names as is in the source)?
4

2 回答 2

1

在之外set_trace_func,您可以使用Module.method_added

class Test
  def self.method_added(method_name)
    puts "#{method_name} added to #{self}"
  end

  def foo
    "foo"
  end
end

$ ruby test.rb
# => foo added to Test
于 2012-10-07T18:21:34.343 回答
0

检查文档。

Kernel.set_trace_funcproc 允许您捕获id参数。这——大多数时候——是函数名。

但是,从您的示例中学习,您还可以使用eval("__method__", binding)...获取当前运行的方法,但我认为这只会获取您在类中定义的方法。

于 2013-10-11T06:23:48.400 回答