is there a way in Ruby to find the calling method name inside of a method?
For example:
class Test
def self.foo
Fooz.bar
end
end
class Fooz
def self.bar
# get Test.foo or foo
end
end
is there a way in Ruby to find the calling method name inside of a method?
For example:
class Test
def self.foo
Fooz.bar
end
end
class Fooz
def self.bar
# get Test.foo or foo
end
end
Use
caller_locations(1,1)[0].label
(for ruby >= 2.0)Edit: My answer was saying to use
__method__
but I was wrong, it returns the current method name.How about
Much cleaner imo.
or perhaps...
In Ruby 2.0.0, you can use:
It's much faster than the Ruby 1.8+ solution:
Will get included in
backports
when I get the time (or a pull request!).Instead you can write it as library function and make a call wherever needed. The code goes as follows :
To trigger the above module method you need to call like this:
caller = CallChain.caller_method
code reference from
I use