Is there away to access the name of the currently defined function?
Example: Right now I do tracing like this:
def myfunc(a,b)
trace.debug “ENTER myfunc a=#{a} b=#{b}”
…
trace.debug “LEAVE myfunc result=#{result}”
result
end
If I rename myfunc, I also have to change the word myfunc in the
trace statements. It would be convenient to have something like
trace.debug “ENTER #{function} a=#{a} b=#{b}”
Maybe Ruby already provides such a feature, and I just don’t know it…
Ronald
Ronald F. wrote:
Is there away to access the name of the currently defined function?
Example: Right now I do tracing like this:
def myfunc(a,b)
trace.debug “ENTER myfunc a=#{a} b=#{b}”
…
trace.debug “LEAVE myfunc result=#{result}”
result
end
If I rename myfunc, I also have to change the word myfunc in the
trace statements. It would be convenient to have something like
trace.debug “ENTER #{function} a=#{a} b=#{b}”
Maybe Ruby already provides such a feature, and I just don’t know it…
Ronald
Include this somewhere:
class Object
def current_method
caller[0] =~ /\d:in `([^’]+)’/
$1
end
end
Then use it:
def abc
puts “ENTERING: #{current_method}”
…
end
Gives: “ENTERING abc”
best,
Dan
On Jul 16, 10:56 am, “Ronald F.” [email protected]
wrote:
If I rename myfunc, I also have to change the word myfunc in the
trace statements. It would be convenient to have something like
trace.debug “ENTER #{function} a=#{a} b=#{b}”
Facets has this Kernel method for it.
module Kernel
def called
/\`([^\']+)\'/.match(caller(1).first)[1].to_sym
end
end
See http://facets.rubyforge.org.
I think the plan for 1.9 is to have method and callee, which
differ based on aliasing. (Guess Matz decided shadow methods are
here to stay).
T.
The caller() method has what you’re looking for.
Here’s my equivalent of what you do:
dbg ‘some stuff’, an_object
def dbg *args
if ENV[‘RAILS_ENV’] == ‘test’
stack = caller(1).slice(0, 5)
$stdout << “==========================\n”
pp(*args)
stack.each do |s|
puts s
end
end
end