如何在ruby模块之间共享方法

时间:2011-09-01 04:25:07

标签: ruby module

以下是我的尝试:

module A
  def self.method1; "method1"; end
  def method2; "method2"; end
end

module B; include A; end

B.method1  # => error
B.method2  # => error
B::method1 # => error
B::method2 # => error

我想避免在两个模块之间复制和粘贴等效代码。我在这里使用模块而不是类的原因是因为我不需要每个模块的多个实例,因为它们只是保持常量(此时其他模块)。

解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:7)

普通include仅为您提供实例方法(特定代码段中的method2)。如果您想共享模块级方法 - 将它们提取到单独的模块和extend其他模块:

module A
  extend self     # to be able to use A.method1

  def method1
    "method1"
  end
end

module B
  extend A
end

B.method1       # => "method1"

也可以通过include获取模块级方法,但稍微扭曲一下,使用钩子方法:

module A
  def self.included(other)
    other.extend ModuleMethods    # this is where the magic happens
  end

  def instance_method
    'instance method'
  end

  module ModuleMethods
    def module_method
      'module method'
    end
  end

  extend ModuleMethods     # to be able to use A.module_method
end


module B
  include A
end

B.module_method        #=> "module method"
B.instance_methods     #=> [:instance_method]

答案 1 :(得分:1)

首先,请注意A.method2也不起作用。您可以创建包含A的{​​{1}}(或B)对象:

method2

因此,对于class C include B # (or A) end c = C.new c.method2 ,它只是按照您的意图运作。

关于method2,它是对象method1的单例方法,无法继承它。

相关问题