这是我尝试过的:
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
Run Code Online (Sandbox Code Playgroud)
我想避免在两个模块之间复制和粘贴等效代码.我在这里使用模块而不是类的原因是因为我不需要每个模块的多个实例,因为它们只是保持常量(此时其他模块).
解决这个问题的最佳方法是什么?
Plain 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"
Run Code Online (Sandbox Code Playgroud)
也可以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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2605 次 |
| 最近记录: |