我有这样的模块结构:
module Parent
PARENT_CONST = 'parent const'
def Parent.meth
puts 'parent meth'
end
end
module Child
include Parent
end
这按预期工作:
puts Parent::PARENT_CONST
=> parent const
Parent.meth
=> parent meth
我可以从子级访问父级的常量,但不能访问方法。像这样:
Child::PARENT_CONST
=> parent const
Child.meth
=> in `<main>': undefined method `meth' for Child:Module (NoMethodError)
我有办法做到这一点吗?
最佳答案
以下是将包含常量、实例方法和类方法的模块混合到一个类中的常见方法,但也可以用于在另一个模块中包含一个模块的常量和类方法,这就是您想要的去做。它使用“回调”或“ Hook ”方法Module#included 。 Object#extend在作为 extend
接收者的模块的参数的模块中添加实例方法。下面它在模块 Child
中的 Public::C_Meths
类方法中创建了实例方法(这里只有一个)。
module Parent
module I_Meths
PARENT_CONST = 'parent const'
end
module C_Meths
def cmeth
'cmeth'
end
end
def self.included(mod)
mod.include(I_Meths)
mod.extend(C_Meths)
end
end
module Child
include Parent
end
Child::PARENT_CONST
#=> "parent const"
Child.cmeth
#=> "cmeth"
更常见的是使用此构造将包含约束、实例方法和类方法的模块混合到类中。
假设我们要添加实例方法:
def imeth
'imeth'
end
到模块 Parent::I_Meths
并在类中包含 Parent
:
class A
include Parent
end
然后
A::PARENT_CONST
#=> "parent const"
A.cmeth
#=> "cmeth"
A.new.imeth
#=> "imeth"
关于Ruby 模块包含,无法访问包含的方法,只能访问常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189062/