Is it possible to include external routes files into the main routes.rb file?

routes, ruby, ruby-on-rails

Solution

(I've updated this answer to take advantage of the RouteReloader for development work)

You can easily accomplish this (even in Rails 4!).

config/routes.rb:

Rails.application.routes.draw do
  resources :foo
end

config/routes/included.rb:

Rails.application.routes.draw do
  resources :bar
end

config/initializers/routes.rb

Rails.application.routes_reloader.paths.unshift *Dir[File.expand_path("../../routes/**/*.rb", __FILE__)]

This will add all files under config/routes to the application routes, and it'll probably add them in reverse lexical order by filename. If you want to load the routes in a different order, rather than the glob, you can just push or unshift the routes onto routes_reloader.paths in the order desired.

rake routes:

   Prefix Verb   URI Pattern             Controller#Action
foo_index GET    /foo(.:format)          foo#index
          POST   /foo(.:format)          foo#create
  new_foo GET    /foo/new(.:format)      foo#new
 edit_foo GET    /foo/:id/edit(.:format) foo#edit
      foo GET    /foo/:id(.:format)      foo#show
          PATCH  /foo/:id(.:format)      foo#update
          PUT    /foo/:id(.:format)      foo#update
          DELETE /foo/:id(.:format)      foo#destroy
bar_index GET    /bar(.:format)          bar#index
          POST   /bar(.:format)          bar#create
  new_bar GET    /bar/new(.:format)      bar#new
 edit_bar GET    /bar/:id/edit(.:format) bar#edit
      bar GET    /bar/:id(.:format)      bar#show
          PATCH  /bar/:id(.:format)      bar#update
          PUT    /bar/:id(.:format)      bar#update
          DELETE /bar/:id(.:format)      bar#destroy

Problem

I have a large number of routes that I would like to separate into different route files. I created a "routes-secondary.rb" and added some routes there. I then tried to add something like this in the app's main routes.rb: require "#{Rails.root}/config/routes-secondary.rb" That does not work however because Rails doesn't recognize the routes in routes-secondary.rb. Is there a way to do this correctly?

Original source

Related problems