Stop Rails from unloading a module in development mode

限于喜欢 提交于 2020-01-22 12:46:53

问题


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


回答1:


In your environment file before referencing MyModule, use require to load the file.

require 'my_module'

this bypasses the dynamic dependency loading mechanism.



来源:https://stackoverflow.com/questions/2419391/stop-rails-from-unloading-a-module-in-development-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!