Engines and routes - a simple solution

Tim Morton bio photo By Tim Morton

So the new Engines feature in Rails 2.3 is great, but there’s one big problem with the way it handles routes. The routes in all of your engines are loaded before your application routes. This is a big problem if your engines have a catch-all default route for a CMS-type thing.

The Thoughtbot guys have one solution which involves alias_method_chain and the ActionController internals. Fortunately, there’s a much simpler way.

  • In your engine, rename routes.rb to my_routes.rb.
  • At the end of your application routes.rb file, add this line:
    ActionController::Routing::Routes.add_configuration_file(
      "#{RAILS_ROOT}/vendor/plugins/cms/config/my_routes.rb")
    (“cms” is the engine name, replace it with your own)
  • That line goes outside the block that covers the rest of the routes.rb file.