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

use*_*830 2 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
Run Code Online (Sandbox Code Playgroud)

假设one_other_method是某种B类的方法.我收到一条错误消息.如何one_other_methodMod不收到此错误的情况下拨打电话?

Aru*_*hit 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 
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做

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
Run Code Online (Sandbox Code Playgroud)

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

  def self.some_method(base)
      base.new.one_other_method
  end
Run Code Online (Sandbox Code Playgroud)

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

现在,如果你定义 -

def some_method
  one_other_method
end
Run Code Online (Sandbox Code Playgroud)

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