[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Accessing the name of the current function

Ronald Fischer

7/16/2007 2:56:00 PM

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 Fischer <ronald.fischer@venyon.com>
Phone: +49-89-452133-162

3 Answers

Daniel Lucraft

7/16/2007 4:03:00 PM

0

Ronald Fischer 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

--
Posted via http://www.ruby-....

Trans

7/16/2007 4:14:00 PM

0



On Jul 16, 10:56 am, "Ronald Fischer" <ronald.fisc...@venyon.com>
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}"

Facets has this Kernel method for it.

module Kernel

def called
/\`([^\']+)\'/.match(caller(1).first)[1].to_sym
end

end

See http://facets.rub....

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.


James Moore

7/16/2007 4:21:00 PM

0

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