Stop Rails from unloading a module in development mode

Posted by Gareth on Stack Overflow See other posts from Stack Overflow or by Gareth
Published on 2010-03-10T18:12:55Z Indexed on 2010/03/11 4:39 UTC
Read the original article Hit count: 254

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-specific 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? :-/

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about dependencies