Ruby中有沒有一種方法可以在方法內部找到調用方法的名稱?例如:class Test def self.foo Fooz.bar endendclass Fooz def self.bar # get Test.foo or foo endend
3 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
在Ruby 2.0.0中,您可以使用:
caller_locations(1,1)[0].label
它比Ruby 1.8+解決方案快得多:
caller[0][/`([^']*)'/, 1]
backports當我有時間(或請求請求?。r將包含在其中。

阿晨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
- 3 回答
- 0 關注
- 663 瀏覽
添加回答
舉報
0/150
提交
取消