In most monolithic Rails projects, the routes.rb file gets huge. Here’s a little trick to split it into smaller files for readability.
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
/config/routes to the auto load path, or require it manually. Add the following to your application.rb
Now we can create the file containing the admin namespace:
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
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.