我创建了一个包含常量NAME
和方法的模块hello
。如果一个类包含该模块,则两个定义都应该在不同的范围内可见。
module A
NAME = 'Otto'
def self.included(base)
base.extend(ClassMethods)
end
def hello(name = 'world')
self.class.hello(name)
end
module ClassMethods
def hello(name = 'world')
"Hello #{name}!"
end
end
end
class B
include A
def instance_scope
p [__method__, hello(NAME)]
end
def self.class_scope
p [__method__, hello(NAME)]
end
class << self
def eigen_scope
p [__method__, hello(NAME)]
end
end
end
B.new.instance_scope
B.class_scope
B.eigen_scope
#=> script.rb:34:in `eigen_scope': uninitialized constant Class::NAME (NameError)
from script.rb:41
但是该常量在 eigenclass 的实例方法范围内不可见,class << self
.
有没有办法使模块更健壮并在上述错误范围内提供常量?