Rails重新加载类和'已从模块树中删除但仍处于活动状态!' 引发ArgumentError

Seb*_*ian 9 instrumentation ruby-on-rails ruby-on-rails-4.1

我在Rails应用程序中编写了自定义检测.我在这样的config/initializers/instrumentation.rb文件中启用它:

ActiveSupport.on_load(:action_controller) do
  include FooBar::ControllerRuntime
end
Run Code Online (Sandbox Code Playgroud)

但这导致我出错A copy of FooBar::ControllerRuntime has been removed from the module tree but is still active!.我弄清楚我可以通过两种方式解决它:

  • 添加路径可能是'FooBar :: ControllerRuntime is defined toconfig.autoload_one_paths`
  • 定义:to_prepare回调ActionController::Railtie

第二个解决方案如下所示:

config.to_prepare do
  ActionController.include FooBar::ControllerRuntime
end
Run Code Online (Sandbox Code Playgroud)

这个漫长的介绍引出了一个问题:哪种方式更好?首先,我禁止重新加载与我的路径相同的类FooBar::ControllerRuntime.有了第二个,我觉得搞砸是不好的ActionController::Railtie.正确的知道ActionController::Railtie没有定义,to_prepare但如果在下一个版本中会发生什么?

Caf*_*der 4

第一种方法看起来更干净 -

添加路径,其中可能'FooBar::ControllerRuntime被定义为config.autoload_one_paths`

原因-

1)如果你真的想在 lib/extensions.rb 这样的文件中做一些猴子补丁,你可以手动要求它:

在 config/initializers/require.rb 中:

需要“#{Rails.root}/lib/extensions”

2)遵循正确的命名约定,因为您必须列出类和模块。

我不建议为生产应用程序自动加载,但如果这是最后一个选项,那么您当然可以尝试一下。

很好地阅读这里 - http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-product/