7

我有两个具有相同方法名称的模块。当我在某个类中包含两个模块时,只执行最后一个模块的方法。相反,我需要在初始化类时执行两者:

class MyClass
    include FirstModule
    include SecondModule

    def initialize
        foo # foo is contained in both modules but only the one in SecondModules is executed
    end
end

可行吗?

4

2 回答 2

12

正如 Yusuke Endoh 所说,在 Ruby 中一切皆有可能。在这种情况下,你必须忘记说 'foo' 的便利性,并且你必须非常明确地说明你真正想要做什么,就像这样:

class MyClass
  include FirstModule
  include SecondModule
  def initialize
    FirstModule.instance_method( :foo ).bind( self ).call
    SecondModule.instance_method( :foo ).bind( self ).call
  end
end

'FirstModule.instance_method...' 行可以用简单的 'foo' 代替,但通过明确说明,您可以确保无论如何,您都在从您认为的那个 mixin 中调用该方法。

于 2012-10-09T12:37:52.423 回答
7

你能修改包含的模块吗?也许您只是调用super第二个模块?

module M1
  def foo
    p :M1
  end
end

module M2
  def foo
    p :M2
    defined?(super) && super
  end
end

class SC
  include M1
  include M2

  def initialize
    foo
  end
end

SC.new

Or perhaps you actually want to do this?

module M1
  def bar; p :M1 end
end

module M2
  include M1
  def foo; bar; p :M2 end
end

class SC
  include M2
  def initialize; foo end
end

See live demo here

于 2012-10-09T12:48:23.923 回答