In most monolithic Rails projects, the routes.rb file gets huge. Here’s a little trick to split it into smaller files for readability.

Rails.application.routes.draw do
  # A lot of routes
end

This is what your config/routes.rb file looks like by default. Adding simple routes and namespaces is easy enough, but when your project becomes big, the file becomes cluttered. There’s no significant performance impact of having a big routes.rb file, and therefore no performance gain in splitting it up, but I like having a visually clean file while developing.

In my application, I have a couple of namespaces, including a “admin” namespace, so lets extract that into it’s own routes file /config/routes/admin_routes.rb. In order for Rails to load this file, we need to add /config/routes to the auto load path, or require it manually. Add the following to your application.rb

module YourProject
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/config/routes)
  end
end

Now we can create the file containing the admin namespace:

module AdminRoutes
  def self.extended(router)
    router.instance_exec do
      namespace :admin do
        resources :articles
        root to: "dashboard#index"
      end
    end
  end
end

Here we are hooking onto the the router when it’s extended by using the Module#extended method, and we receive the router as an argument. By using Object#instance_exec after being extended by routes.rb, we are in the context of Rails.application.routes.draw and are able to configure our routes as normal.

Going back to the first example, extending the basic routes.rb file is as easy as

Rails.application.routes.draw do
  extend AdminRoutes

  # A lot of routes
end

Hope you find this somewhat useful. I’ve only tested this on Rails 5.0.1, but it should work for Rails 4.x as well.