ruby - 检测方法调用

标签 ruby metaprogramming

我正在尝试在 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/

相关文章:

ruby-on-rails - MongoMapper(或任何其他 Mongodb 适配器)是否有类似 "accepts_nested_attributes_for"的方法?

c++ - 是否可以在编译时检查类型是否派生自模板的某些实例化?

java - java中有getattr、callable等元编程函数吗?

ruby - 在没有 'instance' 引用的情况下调用 Ruby Singleton 的方法

ruby-on-rails - 在 mac os sierra 上,卡在 "Setting up CocoaPods master repo"

ruby-on-rails - ApplicationMailer 默认来自标题而不是电子邮件地址?

c# - C# : Automatic ToString Method 中的元编程

python - 如何在Python中向继承方法添加装饰器而不复制整个方法?

ruby-on-rails - 询问 Ruby 哈希数组

javascript - mustache 模板可以进行模板扩展吗?