2009-12-07 102 views
6

我知道类方法告诉什么是对象类的名称,我怎么知道调用方法的名称?有什么方法可以知道吗?有没有办法知道调用方法?

+4

不,这不是一个有效的问题,所有的,但不必查看来电堆栈通常意味着你做错了什么。 – 2009-12-07 13:35:31

回答

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>