SingletonClass
モジュール内にシングルトンクラスのインスタンスがありますModulename
Modulename::SingletonClass.instance
ハッシュを持っています@hashname
。SingletonClass
に新しいキーを追加するメソッドがあります@hashname
。
に新しいキーを追加すると、コントローラーで@hashname
行うと新しいキーが存在することがわかりますが、で行うと、新しいキーが追加されていないようです。何故ですか?コントローラーからの変更を確認できるのに、シングルトン クラスからの変更を確認できないのはなぜですか?puts @hashname
SingletonClass
@hashname
私が説明しようとしている動作を再現するコードは次のとおりです。
module MyModule
module SubModule
class SingletonClass
include Singleton
def initialize
@items = {}
@items = MyMode.all.map{|c| {c.name => c.secondary_name}}.reduce(:merge)
end
def add_new_item(name, secondary_name)
@items[name] = secondary_name
end
def do_something
@items.each do |k,v|
ap "#{k} => #{v}"
end
end
def another_method
do_something
end
end
end
end
コントローラーからこれを行うと:
singleton = MyModule::SubModule::SingletonClass.instance
singleton.add_new_item('test', 'test1')
次に、これもコントローラーから:
singleton.do_something
新しいアイテムが印刷されるので、良いです。
しかしanother_method
、シングルトン クラス内から呼び出すと、新しいアイテムが追加されていないように見えます