Split your routes.rb file into logical files.

Published on February 09, 2024
Written by Daniel Schoppmann

If you have a typical monolithic Rails application, you have probably already divided your application into logical namespaces or modules. Did you know that you can do the same with your routes?
Typically, all routes are stored in the routes.rb file. But this can get pretty messy when you have hundreds of lines to scan. Fortunately, Rails allows you to split routing files using the internal draw method.
So instead of having one big routing file, we like to split our routes into their selective units. For example, if we have an admin area, an api, and the actual application itself, the routes.rb file can look as simple as this:

Rails.application.routes.draw do
  draw :admin
  draw :api
  draw :app
end

Now each namespace is easy to understand and can be defined on its own, for example in config/routes/admin.rb

namespace :admin do
  # Place your admin routes here
end

Of course, namespaces themselves already come with a decent structure in the routes file, but as said, in very large applications, splitting your routes into smaller files may help for better clarity.

Subscribe to get future articles via the RSS feed .