如何使用Rails 6/Zeitwerk在Rails初始化程序中预加载问题? [英] How can I preload concerns in a rails initializer using Rails 6/Zeitwerk?

查看:156
本文介绍了如何使用Rails 6/Zeitwerk在Rails初始化程序中预加载问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个初始化程序,该初始化程序通过将一些应用程序关注点包含到第三方库中来对应用程序进行一些猴子修补.基本上:

I'm working with an initializer that does some monkey patching on app start by including some app concerns into a third party lib. Basically:

# config/initializers/my_initializer.rb

class SomeExternalLib
  include MyConcern1
  include MyConcern2
end

这在Rails 5.2.3中工作正常,但是在升级到Rails 6时我收到了以下弃用消息:

This works fine in Rails 5.2.3, but I got the following deprecation message when upgrading to Rails 6:

不建议使用警告:初始化会自动加载常量MyConcern1和MyConcern2.

DEPRECATION WARNING: Initialization autoloaded the constants MyConcern1, and MyConcern2.

不建议这样做.初始化期间将自动加载 在将来的Rails版本中会成为错误情况.

Being able to do this is deprecated. Autoloading during initialization is going to be an error condition in future versions of Rails.

重新加载不会重新启动应用程序,因此在执行过程中执行了代码 初始化不会再次运行.因此,例如,如果您重新加载ApplicationHelper, 预期的更改将不会反映在该过时的Module对象中.

Reloading does not reboot the application, and therefore code executed during initialization does not run again. So, if you reload ApplicationHelper, for example, the expected changes won't be reflected in that stale Module object.

这些自动加载的常量已被卸载.

These autoloaded constants have been unloaded.

请查看自动加载和重新加载常量"指南以获取解决方案. (从/Users/myuser/code/myapp/config/environment.rb:7调用)

Please, check the "Autoloading and Reloading Constants" guide for solutions. (called from at /Users/myuser/code/myapp/config/environment.rb:7)

我的担忧在应用程序/控制器/问题/中.经过一番调查,我发现该路径没有被自动加载,但是我无法弄清楚如何使Zeitwerk(Rails 6的新自动加载器)动态地加载该路径.我尝试按照描述的

My concerns are in app/controllers/concerns/. After some investigation, I figured out that that path wasn't being autoloaded, but I can't figure out how to make Zeitwerk—Rails 6's new autoloader—load this dynamically. I tried following the pattern for STI autoloading described here, but no luck. Any idea how to address this deprecation warning?

推荐答案

如@Glyoko的答案所述,在依赖项上使用require可以防止在初始化程序中自动加载.但是,如@Puhlze在他的评论中提到的那样,这样做会导致重新加载过程中出现问题.

As described by @Glyoko's answer, using require on dependencies prevents autoloading in initializers. However, doing so leads to problems during reloading as @Puhlze mentioned in his comment.

我在这篇文章中偶然发现了一种使用Rails.configuration.to_prepare的替代方法. .

I stumbled across an alternate approach that utilizes Rails.configuration.to_prepare in this post.

一个例子是:

# config/initializers/my_initializer.rb

Rails.configuration.to_prepare do
  class SomeExternalLib
    include MyConcern1
    include MyConcern2
  end
end

请注意,此操作在开发中的每个请求之前运行,但在渴望加载到生产中之前仅运行一次.

Note that this runs before every request in development but only once before eager loading in production.

它似乎也可以重新加载.

it appears to also work with reloading.

这篇关于如何使用Rails 6/Zeitwerk在Rails初始化程序中预加载问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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