Accessing the name of the current function

R

Ronald Fischer

Is there away to access the name of the currently defined function?
Example: Right now I do tracing like this:

def myfunc(a,b)=20
trace.debug "ENTER myfunc a=3D#{a} b=3D#{b}"
....
trace.debug "LEAVE myfunc result=3D#{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=3D#{a} b=3D#{b}"

Maybe Ruby already provides such a feature, and I just don't know it...

Ronald
--=20
Ronald Fischer <[email protected]>
Phone: +49-89-452133-162
 
D

Daniel Lucraft

Ronald said:
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
 
T

Trans

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}"

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.
 
J

James Moore

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

- James Moore
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top