如何在Ruby中检索调用者上下文对象?

以下是我要简化的代码片段,以避免在每次调用时传递额外的参数。 实际上,我的用例是M是一个用户库,没有在每个方法上定义context参数。 check是一种未由用户定义的方法。

 # User code module M def do_something(context) puts "Called from #{context}" context.check end module_function :do_something end # Application code class Bar def check puts "Checking from #{self}..." end end class Foo < Bar def do_stuff(scope, method) scope.send method, self end end # Executed by user Foo.new.do_stuff M, :do_something 

有没有办法做同样的想法,而不通过self作为do_something方法的输入参数,以检索check方法?

 # User code module M def do_something called_from_object = ??? puts "Called from #{called_from_object}" called_from_object.check end module_function :do_something end # Application code class Bar def check puts "Checking from #{self}..." end end class Foo < Bar def do_stuff(scope, method) scope.send methood end end # Executed by user Foo.new.do_stuff M, :do_something 

感谢您的支持!

遇到这个post,同时为我自己的目的寻找答案。

没有找到合适的,所以我挖掘了Ruby源并组合了一个扩展。 我把它捆绑为gem-只要你使用Ruby 1.9.1就应该没有任何问题安装:

sudo gem install sender

不适用于Ruby 1.8,因为1.8具有不同的跟踪帧模型。

http://rubygems.org/gems/sender

不是你要求的,但如果Foo要包括M那会让你实现你所追求的目标吗? 例如

 module M def do_something puts "I am going to use the test method from the including class" test end end class Foo include M def test puts "In Foo's test method" end def do_stuff do_something end end 

然后你可以这样做:

 irb(main):019:0> Foo.new.do_stuff I am going to use the test method from the including class In Foo's test method 

如果想要让模块提供一些通用function并在类中具有细节,那么这是ruby中相当常见的模式,例如Comparable模块需要包含类来实现<=>