How to get the name of the calling method?

2020-01-23 05:20发布

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

标签: ruby
7条回答
放我归山
2楼-- · 2020-01-23 05:55

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.

查看更多
冷血范
3楼-- · 2020-01-23 05:56

How about

caller[0].split("`").pop.gsub("'", "")

Much cleaner imo.

查看更多
老娘就宠你
4楼-- · 2020-01-23 05:59
puts caller[0]

or perhaps...

puts caller[0][/`.*'/][1..-2]
查看更多
▲ chillily
5楼-- · 2020-01-23 06:06

In Ruby 2.0.0, you can use:

caller_locations(1,1)[0].label

It's much faster than the Ruby 1.8+ solution:

caller[0][/`([^']*)'/, 1]

Will get included in backports when I get the time (or a pull request!).

查看更多
一夜七次
6楼-- · 2020-01-23 06:06

Instead you can write it as library function and make a call wherever needed. The code goes as follows :

module CallChain
  def self.caller_method(depth=1)
    parse_caller(caller(depth+1).first).last
  end

  private

  # Copied from ActionMailer
  def self.parse_caller(at)
    if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at
      file   = Regexp.last_match[1]
      line   = Regexp.last_match[2].to_i
      method = Regexp.last_match[3]
      [file, line, method]
    end
  end
end

To trigger the above module method you need to call like this: caller = CallChain.caller_method

code reference from

查看更多
老娘就宠你
7楼-- · 2020-01-23 06:12

I use

caller[0][/`([^']*)'/, 1]
查看更多
登录 后发表回答