[英]How to share methods between ruby modules
Here is what I tried: 这是我尝试过的:
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
I want to avoid copying and pasting equivalent code between two modules. 我想避免在两个模块之间复制和粘贴等效代码。 The reason I'm using modules instead of classes here is because I don't need more than one instance of each module, as they simply hold constants (other modules, at this point). 我在这里使用模块而不是类的原因是因为我不需要每个模块的多个实例,因为它们只是保持常量(此时其他模块)。
What is the best way to solve this problem? 解决这个问题的最佳方法是什么?
Plain include
only gives you instance methods ( method2
in your particular piece of code). Plain include
仅为您提供实例方法(特定代码段中的method2
)。 If you want to share module-level methods - extract them to separate module and extend
other modules with it: 如果要共享模块级方法 - 将它们提取到单独的模块并使用它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"
It is also possible get module-level methods by include
, but with a little twist, using hook method: 也可以通过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]
First of all, please note that A.method2
won't work either. 首先,请注意A.method2
也不起作用。 You can create objects including A
(or B
) that will have method2
: 您可以创建对象,包括A
(或B
),将有method2
:
class C
include B # (or A)
end
c = C.new
c.method2
So, for method2
it just works as you intended. 因此,对于method2
它只是工作,你打算。
Regarding method1
, it is a singleton method of the object A
and there is no way to inherit it. 关于method1
,它是对象A
的单例方法,没有办法继承它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.