【问题标题】:Strange SimpleDelegator behavior奇怪的 SimpleDelegator 行为
【发布时间】:2013-08-12 09:36:21
【问题描述】:

我的代码使用SimpleDelegator

require 'delegate'

class Foo < SimpleDelegator
  def meth
    p 'new_meth'
  end
end

class Bar
  def meth
    p 'old_meth'
  end

  def bar_meth
    meth
  end
end

bar = Bar.new
foo = Foo.new(bar)
foo.meth      #=> "new_meth"
foo.bar_meth  #=> "old_meth"

为什么最后一行给出"old_meth"???!!!谢谢!

【问题讨论】:

    标签: ruby delegation


    【解决方案1】:

    Delegator 说:

    这个库提供了三种不同的方法来将方法调用委托给一个对象。最容易使用的是 SimpleDelegator将一个对象传递给构造函数,该对象支持的所有方法都会被委托。这个对象以后可以更改。

    好的,现在看一下输出,它位于符号# =&gt; 的右侧。

    require 'delegate'
    
    class Foo < SimpleDelegator
      def meth
        p 'new_meth'
      end
    end
    
    class Bar
      def meth
        p 'old_meth'
      end
    
      def bar_meth
        self.method(:meth)
      end
    end
    
    bar = Bar.new # => #<Bar:0x8b31728>
    foo = Foo.new(bar)
    foo.__getobj__ # => #<Bar:0x8b31728>
    foo.bar_meth # => #<Method: Bar#meth>
    foo.method(:meth) # => #<Method: Foo#meth>
    

    因此,当我使用foo.method(:meth) 行时,输出(#&lt;Method: Foo#meth&gt;)确认无论何时您将调用foo.meth,然后将调用Foo 类的meth 方法。但是@987654331 行@output(#&lt;Method: Bar#meth&gt;) 只是说在方法bar_meth 内部,如果你调用meth 方法,那么Bar#meth 将被调用。

    SimpleDelegator 这么说:

    Delegator 的具体实现,这个类提供了将所有支持的方法调用委托给传递给构造函数的对象的方法,甚至可以在以后使用 #setobj 更改被委托给的对象.

    是的,在您的情况下,foo 对象已通过使用 #__setobj__ 设置为 bar 对象。 foo.__getobj__ 行的输出显示了这一点。

    【讨论】:

    • >> 简单的说在方法bar_meth里面,如果你调用meth方法,那么会调用Bar#meth。为什么?我在哪里可以在文档和代码中看到它?谢谢。
    • 就是这样实现的..文档明确没有提到..但是上面的代码解释了..为什么"old_meth"出来了..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2015-07-20
    • 2010-10-03
    • 2021-07-12
    • 2013-10-04
    • 2019-01-23
    相关资源
    最近更新 更多