在
类Singleton class
中重新定义const_missing
方法似乎Module
不起作用。但是如果我直接在类Module
中重新定义它就可以了。有什么原因吗?
class Module
class << self
def const_missing(constant)
puts "This doesn't work!"
end
end
end
Hello
以下工作在哪里!
class Module
def const_missing(constant)
puts 'This works!'
end
end
Hello
背景:
- 尝试在常量属于不可覆盖的类别的情况下使用
super
。假设与模式不匹配的常量仍会导致NameError
。
为什么你认为在模块的特征类上定义const_missing
不起作用?它完美地工作:
▶ class Module
▷ class << self
▷ def const_missing(constant)
▷ puts "This doesn't work!"
▷ end
▷ end
▷ end
#⇒ :const_missing
▶ Module::F
#⇒ This doesn't work!
问题是你想实现什么?当您调用Module
/Class
调用它时,您是否有兴趣处理常量,例如:
module M ; end
puts M::MissingConst
你应该在M
的特征类上实现const_missing
。哪个单例的超类显然是Module
类本身,而不是模块的特征类(M.singleton_class.superclass => Module
)。
是否要处理不带命名空间的标题大小写名称引用的几乎所有常量,都可以使用:
class Object
class << self
def const_missing(name)
puts 'bingo '
end
end
end
▶ F
#⇒ bingo