MrRoth MrRoth - 1 year ago 85
Ruby Question

ruby get caller full namespace with its parameter name and argument

in debugging ruby applications, i am interested in printing in each function the:
- full method namespace
- the method parameters and their arguments (values)

for instance, given the following code block

module Foo
module Bar
def self.baz(p, q)
end
end
end


when invoking
baz
with arguments, such as
Foo::Bar.baz 'val1', 'val2'
, a message should be printed with the following output
Foo::Bar.baz(p=val1, q=val2)
(or any similar output)

i am familiar with ruby reflection, so i can introduce to each function some additional code to print it. though, single point of modification is a bliss, thus having the each method call another method that will produce such output will be the great.

my questions are:


  1. is there anyway to introduce a method, which each other method invoke that will yield an output similar to the above?

  2. is there anyway to achieve the same result by binding the printing method (function) to the beginning of any other method?


ndn ndn
Answer Source

What you are looking for is #set_trace_func combined with binding introspection:

module Foo
  module Bar
    def self.baz(p, q)
    end
  end
end

intercept_event = proc do |event, _, _, method_name, method_binding, _|
  if event == 'call'
    self_in_method = method_binding.eval('self')

    parameter_names = self_in_method.method(method_name).parameters.map(&:last)
    parameter_list  = parameter_names.map do |name|
      "#{name}=#{method_binding.local_variable_get(name)}"
    end

    puts "#{self_in_method}.#{method_name}(#{parameter_list.join ', '})"
  end
end

set_trace_func intercept_event

Foo::Bar.baz 'val1', 'val2' # Foo::Bar.baz(p=val1, q=val2)

Note that this will not work for C methods. To handle them, you can check for 'c-call' instead of 'call'. You will have to move the method parameters in the string eval however, as self in those methods is not the same as in Ruby methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download