Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g. 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)

like image 411
Benedikt B Avatar asked Feb 13 '15 12:02

Benedikt B


1 Answers

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
like image 114
janfoeh Avatar answered Sep 22 '22 21:09

janfoeh