以下是我想要简化的代码片段,以避免在每次调用时传递额外的参数。事实上,我的用例是 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
感谢您的支持!
最佳答案
在出于我自己的目的寻找答案时偶然发现了这篇文章。
没有找到合适的,所以我翻阅了 Ruby 源代码并整理了一个扩展。我已经将它捆绑为一个 gem - 只要您使用的是 Ruby 1.9.1,安装应该没有任何问题:
sudo gem install sender
这不适用于 Ruby 1.8,因为 1.8 有不同的跟踪帧模型。
关于ruby - 如何在 Ruby 中检索调用者上下文对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614470/