我知道類方法告訴什麼是對象類的名稱,我怎麼知道調用方法的名稱?有什麼方法可以知道嗎?有沒有辦法知道調用方法?
6
A
回答
10
3
呼叫者是籽粒方法,可以讓你做到這一點,所以呼叫者[0]會讓你知道函數的直接調用方。
快速黑客只得到函數的名稱可能是
caller[0][/`\S+/].chop[1..-1]
這將返回調用方法的名字作爲一個字符串,然後你就可以,但是你想
1
使用Ruby的爲了性能和垃圾收集的原因,使用String
完成了Kernel#caller
的實現。如果你想要做更復雜的調用堆棧分析,看看這個博客帖子:
http://eigenclass.org/hiki/ruby+backtrace+data
筆者經過一個更好的調用棧對象圖的兩種不同的實現,一個在純Ruby與實現(未廣爲人知)Kernel#set_trace_func
方法,另一個作爲MRI的C擴展。
生產應用程序不應該使用Ruby自帶的Kernel#caller
實現以外的任何其他應用程序。如果你廣泛地使用擴展,你可能會最終殺死Ruby有效地進行垃圾收集,並使你的過程變慢(我估計)達到幾個數量級。
0
你可以寫這樣的事情:
module Kernel
private
def who_is_calling? # Or maybe def who_just_called?
caller[1] =~ /`([^']*)'/ and $1
end
end
然後你有這些小測試:
irb(main):056:0* def this_is_a_method
irb(main):057:1> puts "I, 'this_is_a_method', was called upon by: '#{who_is_calling?}'"
irb(main):058:1> end
=> nil
irb(main):059:0> def this_is_a_method_that_calls_another
irb(main):060:1> this_is_a_method
irb(main):061:1> end
=> nil
irb(main):062:0> this_is_a_method_that_calls_another
I, 'this_is_a_method', was called upon by: 'this_is_a_method_that_calls_another'
=> nil
irb(main):063:0> this_is_a_method
I, 'this_is_a_method', was called upon by: 'irb_binding'
=> nil
irb(main):064:0>
不,這不是一個有效的問題,所有的,但不必查看來電堆棧通常意味着你做錯了什麼。 – 2009-12-07 13:35:31