为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

UYOU 2019-10-24 14:23:14
Ruby中有没有一种方法可以在方法内部找到调用方法的名称?例如:class Test  def self.foo    Fooz.bar  endendclass Fooz  def self.bar    # get Test.foo or foo  endend
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

puts caller[0]

也许...


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


查看完整回答
反对 回复 2019-10-24
?
繁星coding

TA贡献1797条经验 获得超4个赞

在Ruby 2.0.0中,您可以使用:


caller_locations(1,1)[0].label

它比Ruby 1.8+解决方案快得多:


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

backports当我有时间(或请求请求!)时将包含在其中。


查看完整回答
反对 回复 2019-10-24
?
阿晨1998

TA贡献2037条经验 获得超6个赞

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


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


查看完整回答
反对 回复 2019-10-24
  • 3 回答
  • 0 关注
  • 580 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信