如何在Ruby中检索调用者上下文对象? [英] How to retrieve caller context object in Ruby?
问题描述
此后是我想简化的代码段,以避免在每次调用时传递额外的参数.实际上,我的用例是M
是一个用户库,在每个方法上都没有定义context
参数. check
是用户未定义的方法.
hereafter is my piece of code that I want to simplify in order to avoid passing an extra argument on each call. In fact, my usecase is that M
is a user library without the definition of context
argument on each method. check
is a method that is not defined by the user.
# 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
方法?
Is there a way to do the same think without passing self
as an input argument to do_something
method in order to retrieve check
method ?
# 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
感谢您的支持!
推荐答案
在为我自己的目的寻找答案的同时,也喜欢这篇文章.
Came across this post while looking for an answer for my own purposes.
找不到合适的扩展程序,因此我翻阅了Ruby源代码并整理了一个扩展.我已经将其捆绑为gem-只要您使用的是Ruby 1.9.1,就可以毫无问题地安装它:
Didn't find one that was appropriate, so I dug through the Ruby source and put together an extension. I've bundled it as a gem- should install without any problem so long as you are using Ruby 1.9.1:
sudo gem安装发件人
sudo gem install sender
此不适用于Ruby 1.8,因为1.8具有用于跟踪帧的不同模型.
This will not work with Ruby 1.8, as 1.8 has a different model for tracking frames.
http://rubygems.org/gems/sender
这篇关于如何在Ruby中检索调用者上下文对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!