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

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

例如:

class Test
def self.foo
Fooz.bar
end
end


class Fooz
def self.bar
# get Test.foo or foo
end
end
84937 次浏览
puts caller[0]

或者..。

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

我吸毒

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

在 Ruby2.0.0中,您可以使用:

caller_locations(1,1)[0].label

它是 快多了而不是 Ruby 1.8 + 解决方案:

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

将得到包括在 backports当我得到的时间(或拉请求!)。

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

编辑 : 我的回答是使用 __method__,但是我错了,它返回当前方法名。

怎么样

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

干净多了。

相反,你可以把它写成库函数,并在需要的地方调用它:

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

来自... 的代码引用

为了查看任何语言(无论是 Ruby、 Java 还是 python)中的调用方和被调用方信息,您总是希望查看堆栈跟踪。在一些语言中,比如 Rust 和 C + + ,编译器中内置了一些选项,可以打开某种可以在运行时查看的分析机制。我相信 Ruby 有一个叫 Ruby 教授的人。

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

基本上,您需要了解的关于这个命令的全部内容如下:

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