我正在尝试在 ruby 中实现延迟方法执行。假设我有一个包含两个方法的类,这些方法不应在调用后立即执行
class Foo
lazy_evaluate :bar, :baz
def bar(string)
puts string
end
def baz(hash)
puts hash.inspect
end
end
f = Foo.new
f.bar('hello world') => nil
f.baz(hello: :world) => nil
f.run_lazy_methods =>
'hello world'
'{:hello=>:world}'
我不想在我的 gem 中使用它 http://pastie.org/5137463
我正在询问如何实现此行为
最佳答案
使用委托(delegate)对象,将调用的方法记录到堆栈上,然后在委托(delegate)上重放它们。
class LazyObject
def initialize(delegate)
@invocations = []
@delegate = delegate
end
def bar(*args, &block)
@invocations << {
method: :bar,
args: args,
block: block
}
end
def baz(*args, &block)
@invocations << {
method: :baz,
args: args,
block: block
}
end
def run_lazy_methods
@invocations.each do |inv|
@delegate.send(
inv[:method],
*inv[:args],
&inv[:block]
)
end
end
end
obj = LazyObject.new(RealObject.new)
obj.bar(hello: :world)
obj.baz("Hello World")
obj.run_lazy_methods
你可以使用method_missing
更好地编写上面的内容,但我想说清楚;)
关于ruby - 检测方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13139899/