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

查看:26
本文介绍了如何使用 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)

我的担忧在 app/controllers/concerns/中.经过一番调查,我发现该路径没有被自动加载,但我不知道如何让 Zeitwerk(Rails 6 的新自动加载器)动态加载它.我尝试遵循描述的 STI 自动加载模式 这里,但没有运气.知道如何解决这个弃用警告吗?

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.

我在 这篇文章.

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天全站免登陆