定数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
に表示されません。
モジュールをより堅牢にし、上記のエラーのある範囲でも定数を提供する方法はありますか?
感謝を。私は何か新しいことを学んだ! –
@EricDuminilまったくありません!あなたの説明は非常に便利です。 – sschmeck