开发者

Module gets reloaded every request so initialized data are lost

I store a value in a class variable inside of a module, such as:

module TranslationEnhancer
  def self.install! klass
    @dictionaries ||= [] << klass
  end
  ...
end

I call this from an initializer in config/initializers:

require Rails.root + "lib" + "translation_enhancer.rb"
TranslationEnhancer::install! TranslationDictionary

Now, if I start the server in development environment, everything is ok during the first request. However, after that request, @dictionaries are suddenly nil. I have commented all other code in TranslationEnhancer, so I am absolutely sure the whole module must get reloaded every time I do a request.

I tried to move the module outside of the lib directory (moved it to lib_unloadable), then I tried:

ActiveSupport::Dependencies.explicitly_unloadable_constants << "TranslationEnhancer" 

but failed again. I have no idea how to solve this, please help.

Got Ruby 1.9.2 @ Rails 3.1.rc4.

EDIT: I 开发者_如何学运维know I could set the dictionaries as a constant. But I would like to use TranslationEnhancer as a library - so I could use it unchanged in a different project and install different Directories, such as:

TranslationEnhancer.install! EnglishDirectory, FrenchDirectory

These values won'd change during the runtime, they will just change project to project.


Solved!

I realized that the whole application.rb and environment.rb files are reloaded along with all other files. The only thing that does not get reloaded are initializers (config/initializers/*). The solution was to move the initialization to application.rb.


@dictionaries is not a "class variable". It is a "class-level instance variable". Look here for a better explanation: Class and instance variables

Try using @@dictionaries instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜