在包含的模块中调用继承的方法

时间:2014-04-04 10:59:20

标签: ruby module

假设我有

module Mod
  def self.included(base)
    some_method
  end
  def self.some_method
    one_other_method
  end
end

class A < B 
  include Mod
end

假设one_other_methodB类的某种方法。我收到一条错误消息。如何在不收到此错误的情况下从one_other_method致电Mod

2 个答案:

答案 0 :(得分:5)

为此你需要稍微改变设计:

module Mod
  def self.included(base)
      some_method(base)
  end
  def self.some_method(base)
      base.new.one_other_method
  end
end

class A < B 
  include Mod
end 

或者你可以这样做

module Mod
  def self.included(base)
      base.new.some_method
    end
  def some_method
      one_other_method
  end
end

class A < B 
  include Mod
end

重点是 - 如果您将方法定义如下

  def self.some_method(base)
      base.new.one_other_method
  end

some_method将仅限于模块Mod,因为模块单例方法不会分配给您将包含它的类/模块。这就是原因,你需要以不同的方式思考它。我不知道你的最终设计目标,所以我不能告诉你什么更适合你,我会说你,这些是我所知道的两种方法。

现在,如果你定义 -

def some_method
  one_other_method
end

some_method将作为A的实例方法提供,另一方面,class A < B ..one_other_method也可用作{{1}的实例方法}}。因此,2中的任何一个都可以愉快地调用其中的其他人,而没有明确的接收者,因为 Ruby 本身将为您设置A

答案 1 :(得分:2)

如果您想玩得开心,还可以查看super_module

require 'super_module'
module Mod
  include SuperModule

  def self.some_method
    one_other_method
  end

  some_method
end

class A < B 
  include Mod
end
相关问题