Split your Rails routes into smaller files
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
add /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.
Recent Posts
Extend ActiveStorage::Blob with callbacks
ActiveStorage is currently missing both validations and callbacks, but you can easily extend it with the callbacks you need.
Writing a custom analyzer for ActiveStorage
Writing custom analyzers for your ActiveStorage blogs is not well documented, but quite easy. This is how I implemented a simple EDI file analyzer for my neverending hobby project.
Manjaro/Arch: transfer packages to another computer
How to make a backup of all installed packages on a Arch/Manjaro distro, and install them on a different machine.