这是我尝试过的: module A def self.method1; "method1"; end def method2; "method2"; endendmodule B; include A; endB.method1 # = errorB.method2 # = errorB::method1 # = errorB::method2 # = error 我想避免在两个模块之间复制和
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
我想避免在两个模块之间复制和粘贴等效代码.我在这里使用模块而不是类的原因是因为我不需要每个模块的多个实例,因为它们只是保持常量(此时其他模块).
解决这个问题的最佳方法是什么?
Plain include仅为您提供实例方法(特定代码段中的method2).如果要共享模块级方法 – 将它们提取到单独的模块并使用它扩展其他模块: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来获取模块级方法,但稍微扭曲一下,使用hook方法:
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]