sawa
sawa

Reputation: 168269

Getting the name of the defined method

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)?

Upvotes: 4

Views: 133

Answers (2)

Igbanam
Igbanam

Reputation: 6082

Check the documentation.

The Kernel.set_trace_func proc allows you catch an id parameter. This—most times—is the function name.

However, learning from your example, you can also get the current running method using eval("__method__", binding) …but I think this only gets the methods you have defined in your classes.

Upvotes: 0

pje
pje

Reputation: 22757

Outside of set_trace_func, you could use 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

Upvotes: 1

Related Questions