Rails 7 Engine Initializer Hook Not Working

Viewed 233

trying to get my gem working in Rails 7. I have confirmed it works in Rails 6.1.4.1 (latest).

In my engine's engine.rb file I have this...

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine

    initializer "my_engine.include_controller" do |app|
      ActionController::Base.send :include, MyEngine::MyController
    end
  end
end

Upon server start or running a console I get...

uninitialized constant MyEngine::MyController (NameError)

I have the gem controllers in their namespaced directory and to reiterate this works in Rails 6.1.

I have also tried these variations with the same error...

ActionController::Base.include MyEngine::MyController
ActiveSupport.on_load :action_controller_base do
  include MyEngine::MyController
end

If I put the following in the main app's ApplicationController instead then it works...

include MyEngine::MyController

Does anyone have any insight to how these hooks need to be called or should I report this as a bug to the rails team?

1 Answers

I was able to fix the same issue by pushing the required files to the autoload_once_paths configuration. Here an example of a possible fix.

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine

    config.autoload_once_paths << "#{root}/app/controllers"

    initializer "my_engine.include_controller" do |app|
      ActionController::Base.send :include, MyEngine::MyController
    end
  end
end

Sources:

Related