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

后端 未结 2 1334
忘掉有多难
忘掉有多难 2021-01-07 23:27

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/initi         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 23:48

    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.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.

    Edit: it appears to also work with reloading.

提交回复
热议问题