在开发模式下阻止Rails卸载模块 [英] Stop Rails from unloading a module in development mode

查看:85
本文介绍了在开发模式下阻止Rails卸载模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中有一个模块,该模块位于/lib

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

然后从我的environments/#{RAILS_ENV}.rb文件中,为the_variable设置特定于环境的值:

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.

问题在于,在开发模式下,Rails通过ActiveSupport::Dependencies卸载模块的负载,并为新请求及时重新加载它们.通常这是一个很好的行为,因为这意味着您在更改代码时不需要重新启动本地主机服务器.

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.

但是,这也会清除我初始化的the_variable变量,并且当下一个请求进入初始化程序时(显然)不会再次运行.最终结果是,后续请求最终将MyModule.the_variable设置为nil,而不是我要查找的42.

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.

我正在尝试找出如何在请求结束时停止Rails卸载我的模块,或者寻找另一种方法来为我的模块干净地提供特定于环境的配置.

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

推荐答案

在引用MyModule之前,在您的环境文件中,使用require加载文件.

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

require 'my_module'

这绕过了动态依赖项加载机制.

this bypasses the dynamic dependency loading mechanism.

这篇关于在开发模式下阻止Rails卸载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆