クラスメソッドがオブジェクトのクラスの名前を教えてくれることは知っていますが、呼び出し元のメソッドの名前をどのように知ることができますか? それを知る方法はありますか?
4 に答える
callerはこれを可能にするカーネルメソッドであるため、caller[0]は関数の直接の呼び出し元を通知します。
関数の名前だけを取得するための簡単なハックは
caller[0][/`\S+/].chop[1..-1]
これにより、呼び出し元のメソッドの名前が文字列として返されます。この文字列は、必要に応じて使用できます。
Ruby の の実装は、パフォーマンスとガベージ コレクションの理由から s でKernel#caller
行われました。String
より高度なコール スタック分析を行いたい場合は、次のブログ投稿をご覧ください。
http://eigenclass.org/hiki/ruby+backtrace+data
著者は、より優れたコール スタック オブジェクト グラフの 2 つの異なる実装を調べます。1 つは (あまり知られていない)Kernel#set_trace_func
メソッドを使用して純粋な Ruby で実装され、もう 1 つは MRI の C 拡張として機能します。
Kernel#caller
本番アプリケーションでは、Ruby に付属する実装以外は使用しないでください。上記の拡張機能を広範囲に使用すると、Ruby の効果的なガベージ コレクション機能が無効になり、プロセスが最大数桁遅くなる可能性があります (私は推定します)。
次のように書くことができます。
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>