Dav*_*vid 3 ruby metaprogramming
以下是我要简化的代码片段,以避免在每次调用时传递额外的参数.实际上,我的用例是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
Run Code Online (Sandbox Code Playgroud)
有没有办法做同样的思考而不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
Run Code Online (Sandbox Code Playgroud)
感谢您的支持!
遇到这篇文章,同时为我自己的目的寻找答案.
没有找到合适的,所以我挖掘了Ruby源并组合了一个扩展.我把它捆绑为gem-应该安装没有任何问题,只要你使用Ruby 1.9.1:
sudo gem install sender
这不适用于Ruby 1.8,因为1.8具有跟踪帧的不同模型.
http://rubygems.org/gems/sender