如何获取调用方法的名称?

时间:2011-02-24 04:18:12

标签: ruby

Ruby中有没有办法在方法中找到调用方法名?

例如:

class Test
  def self.foo
    Fooz.bar
  end
end

class Fooz
  def self.bar
    # get Test.foo or foo
  end
end

7 个答案:

答案 0 :(得分:191)

puts caller[0]

或者也许......

puts caller[0][/`.*'/][1..-2]

答案 1 :(得分:149)

在Ruby 2.0.0中,您可以使用:

caller_locations(1,1)[0].label

它是much faster而不是Ruby 1.8+解决方案:

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

当我得到时间(或拉取请求!)时,它会被包含在backports中。

答案 2 :(得分:26)

使用caller_locations(1,1)[0].label(对于ruby> = 2.0)

修改:我的回答是说要使用__method__,但我错了,它会返回当前的方法名称,请参阅this gist

答案 3 :(得分:20)

我用

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

答案 4 :(得分:4)

怎么样

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

更清洁的imo。

答案 5 :(得分:2)

相反,您可以将其编写为库函数,并在需要时进行调用。代码如下:

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

要触发上述模块方法,您需要像这样调用: caller = CallChain.caller_method

code reference from

答案 6 :(得分:2)

为了查看任何语言的调用者和被调用者信息,无论是ruby还是java或python,您总是希望查看堆栈跟踪。在某些语言中,例如Rust和C ++,编译器中内置了一些选项,可以打开您在运行时可以查看的某种分析机制。我相信Ruby的存在称为ruby-prof。

如上所述,您可以查看ruby的执行堆栈。此执行堆栈是包含回溯位置对象的数组。

基本上你需要知道的关于这个命令的所有内容如下:

调用者(start = 1,length = nil)→array或nil