Ruby 模块包含,无法访问包含的方法,只能访问常量
Ruby module include, can't access included methods, only constants
我有这样的模块结构:
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)
我有办法做到这一点吗?
下面是将包含常量、实例方法和class方法的模块混合成一个class的常用方法,但也可以用来包含常量和class ] 一个模块在另一个模块中的方法,这就是你想要做的。它使用 "callback" 或 "hook" 方法 Module#included. Object#extend 将作为参数的模块中的实例方法添加到作为 extend
的接收者的模块中。下面它使模块 Child
.
中的 Public::C_Meths
class 方法中的实例方法(这里只有一个)
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"
更常见的是使用此构造将包含约束、实例方法和 class 方法的模块混合到 class.
中
假设我们要添加实例方法:
def imeth
'imeth'
end
到模块 Parent::I_Meths
和 include Parent
在 class:
class A
include Parent
end
然后
A::PARENT_CONST
#=> "parent const"
A.cmeth
#=> "cmeth"
A.new.imeth
#=> "imeth"
我有这样的模块结构:
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)
我有办法做到这一点吗?
下面是将包含常量、实例方法和class方法的模块混合成一个class的常用方法,但也可以用来包含常量和class ] 一个模块在另一个模块中的方法,这就是你想要做的。它使用 "callback" 或 "hook" 方法 Module#included. Object#extend 将作为参数的模块中的实例方法添加到作为 extend
的接收者的模块中。下面它使模块 Child
.
Public::C_Meths
class 方法中的实例方法(这里只有一个)
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"
更常见的是使用此构造将包含约束、实例方法和 class 方法的模块混合到 class.
中假设我们要添加实例方法:
def imeth
'imeth'
end
到模块 Parent::I_Meths
和 include Parent
在 class:
class A
include Parent
end
然后
A::PARENT_CONST
#=> "parent const"
A.cmeth
#=> "cmeth"
A.new.imeth
#=> "imeth"