简体   繁体   中英

How can I add autoload_paths in my Rails4 Engine?

Usually I add the following in config/application.rb to add autload_paths:

config.autoload_paths += Dir[Rails.root.join('app', 'poros', '{**}')]

How can I achieve the same in an engine? It seems to work when I just use the same code in application.rb in the host app, however I think it's ugly that the code is not in the engine and needs to be added to the host app to make things work.

The only solution I found to add the load path through the engine is by adding this to lib/engine/engine.rb:

config.to_prepare do
  Dir.glob(Rails.root + "../../app/poros/**/*.rb").each do |c|
    require_dependency(c)
  end
end

However there seems to be something fundamentally wrong with this as this leads to problems when I'm doing console reloads (eg it tells me that constants are already defined or that concerns can't execute the include block twice)

What is the right way to do this in the engine itself? (can't believe this is so hard/uncommon, I have really googled a lot but I can't find a solution)

According to the Rails::Engine documentation , you can add autoload paths in your Railtie like this:

class MyEngine < Rails::Engine
  # Add a load path for this specific Engine
  config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)

  initializer "my_engine.add_middleware" do |app|
    app.middleware.use MyEngine::Middleware
  end
end

If poros is a subdirectory of app, you do not need add it again.

All subdirectories of app in the application and engines present at boot time. For example, app/controllers. They do not need to be the default ones, any custom directories like app/workers belong automatically to autoload_paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM