我创建了一个包含常量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
但是常量在本征类的实例方法范围中是不可见的class << self
.
有没有办法使模块更健壮,并在上面的错误范围内提供常量?