How can I preload concerns in a rails initializer using Rails 6/Zeitwerk? How can I preload concerns in a rails initializer using Rails 6/Zeitwerk? ruby ruby

How can I preload concerns in a rails initializer using Rails 6/Zeitwerk?


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.

An example would be:

# config/initializers/my_initializer.rbRails.configuration.to_prepare do  class SomeExternalLib    include MyConcern1    include MyConcern2  endend

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

Edit: it appears to also work with reloading.


Would help if I read the error message a bit more closely:

Autoloading during initialization is going to be an error condition in future versions of Rails.

Discussion for the change is here and guide is here.

In short, autoloading shouldn't be done in initializers, and this is going to be phased out. Solutions are to either 1) Don't use stuff that needs to be autoloaded in initializers (preferred, obviously), or 2) explicitly require dependencies in initializers.

So I would do:

# config/initializers/my_initializer.rbrequire 'my_concern1'require 'my_concern2'class SomeExternalLib  include MyConcern1  include MyConcern2end