I have a module in my Rails app that lives in /lib
module MyModule
mattr_accessor :the_variable
class << self
def setup
yield this
end
end
end
From my environments/#{RAILS_ENV}.rb
file I can then set an environment-s开发者_运维技巧pecific value for the_variable
:
MyModule.setup do |my_module_config|
my_module_config.the_variable = 42
end
This is lovely, and it seems to work (almost) fine.
The problem is that in development mode, Rails via ActiveSupport::Dependencies
unloads a load of modules, and reloads them in time for the new request. This is usually a great behaviour because it means you don't need to restart your localhost server when you make a code change.
However, this also clears out my initialised the_variable
variable, and when the next request comes in the initialiser (obviously) isn't run again. The net effect is that subsequent requests end up having MyModule.the_variable
set to nil
rather than the 42
that I'm looking for.
I'm trying to work out how to stop Rails unloading my module at the end of the request, or alternatively find another way to cleanly provide environment specific configuration for my modules.
Any ideas? :-/
In your environment file before referencing MyModule, use require to load the file.
require 'my_module'
this bypasses the dynamic dependency loading mechanism.
精彩评论