Controlling routes loading order from Engines

Viewed 5194

So in Rails3 Engines come with their own models/controllers/views and of course routes. Now the question is: How do you ensure that Engine routes will be loaded before (or after) application routes and all other Engines that are present?

Here's an example of my Rails app routes:

match '*(path)', :to => 'foo_controller#bar_action'

And my Engine:

match '/news', :to => 'bar_controller#foo_action'

So by default Engines routes will be loaded after the application ones. This means that Engine routes are inaccessible due to that catch-all route in my app. How can force Engine routes to be loaded first (or last)?

4 Answers

You can write a method in your engine that can be called to configure your engine's routes:

module MyEngine
    class Engine < Rails::Engine
        def self.configure_routes(mapper)
           mapper.match '/news', :to => 'news_controller#index'
        end
    end
end

This allows you to insert your engine's routes before a catch-all in my_application/config/routes.rb:

Rails.application.routes.draw do
    # routes
    MyEngine::Engine.configure_routes(self)
    # more routes

    # catch-all route
end

Then in the engine's my_engine/config/routes.rb file:

unless Rails.application.routes.named_routes.key?(:news)
  Rails.application.routes.draw do
    MyEngine::Engine.configure_routes self
  end
end

If you're mounting the engine and don't include the explicit route configuration method, the engine routes will be added as usual to the end of the application routes.

Related