Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 326
Jan Minárik Avatar asked Jul 29 '11 19:07

Jan Minárik


1 Answers

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.

like image 58
Jan Minárik Avatar answered Nov 15 '22 18:11

Jan Minárik