如何在ruby模块之间共享方法
发布时间:2020-12-17 01:28:22 所属栏目:百科 来源:网络整理
导读:这是我尝试过的: 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] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |