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

Ruby中有没有一种方法可以在方法内部找到调用方法的名称?


例如:


class Test

  def self.foo

    Fooz.bar

  end

end


class Fooz

  def self.bar

    # get Test.foo or foo

  end

end


UYOU
浏览 584回答 3
3回答

饮歌长啸

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

繁星coding

在Ruby 2.0.0中,您可以使用:caller_locations(1,1)[0].label它比Ruby 1.8+解决方案快得多:caller[0][/`([^']*)'/, 1]backports当我有时间(或请求请求!)时将包含在其中。

阿晨1998

相反,您可以将其编写为库函数,并在需要时进行调用。代码如下: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  endend要触发上述模块方法,您需要这样调用: caller = CallChain.caller_method
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby