Thursday, February 8, 2007

Who's calling, please?

In a search to discover how I could log the calling of any method, I came across the caller method. This returns an array of strings which is the current call stack.

I did this in irb:

puts caller.join("\n")

Results:

/usr/local/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'
/usr/local/lib/ruby/1.8/irb/workspace.rb:52

=> nil


This is the magical "what's the name of the method that called me?" code from here:

def this_method
caller[0] =~ /`([^']*)'/ and $1

end


So you could call this_method from any_method to get the name of the method which would be "any_method" in this case. Follow?

Oh, and I haven't yet figured out how to log a method call the way I want to. In merb you can use a before filter, but your method doesn't call the filter method -- merb does -- so you don't get the method name you want returned using caller.

Updated 13-Feb-2007:

Found the following related method in the merb code:

def current_method_name(depth=0)
   caller[depth] =~ /`(.*)'$/; $1
end

No comments: