Splitting Rails routes into multiple files

By ayates

I was just asked how you would split your Rails routes file into multiple files for instance in the case of having an application frontend and a set of routes serving your application's API.

Now, I have a number of applications which work this way and utilize routing constraints to determine which routes should be used but splitting them into more manageable individual files is a nice idea so, my first thought...

Require the additional routes

You can draw your routes multiple times so the simple solution is to use your main routes.rb file as a manifest, and require the additional routes files e.g.

config/routes.rb

require Rails.root.join('config/routes/frontend.rb')
require Rails.root.join('config/routes/api.rb')

config/routes/frontend.rb

YourApp::Application.routes.draw do
  # Your routes here...
end

But you can also set the load path for your application's routes...

Setting a routes load path

If you want to get rid of your routes file completely, and just have your individual files - you can set the route path in your application's config:

config/application.rb

config.paths.config.routes.concat Dir[Rails.root.join('config/routes/*.rb')]

Now all files in config/routes/ will be loaded without the need for a config/routes.rb file.