Image for post
Image for post
source: unsplash.com

Clean your Rails routes: grouping

How to separate & group your routes by logical entities

Mehdi Farsi
Feb 20, 2020 · 2 min read

In Ruby on Rails, all the routes of a given application can be found within the config/routes.rb file.

You add more and more routes in this file as your project grows.

The problem here is that this file potentially becomes very complicated to manage over the time.

That’s why it’s important to find a way to order and maintain your routes.

Let’s have a look to an example to see how we could achieve this task.

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

The my-blog application

Few month ago, we created our my-blog application. This application provides a way to create and manipulate blogposts.

Also, it provides an admin dashboard.

So the config/routes.rb looks like as following

Here we can clearly isolate 3 entities:

  • The users resource
  • The posts resource
  • The admin namespace

So let’s see how to extract each of these entities in a separate file.

First, we have to manipulate our config/application.rb file

This line will redefine the target of our config.paths['config/routes.rb'].

The target is now all the Ruby files under the config/routes/ directory.

So when your application receives a request, Rails will search the expected route in the routing table defined under the config/routes directory.

Now, let’s have a look to the files in this directory

$> tree config/routes
config/routes
├── base.rb
├── admin.rb
├── posts.rb
└── users.rb
0 directories, 4 files

Note that each file uses the Rails.application.routes.draw method in order to append our resources to the existing routing table.

Finally, you can remove the config/routes.rb file.

Conclusion

With this implementation, As things progress, you’ll be able to maintain your routes in a very easy way.

And that will be a good introduction to your app for new developers.

Voilà!

RubyCademy

E-Learning platform for Ruby and Ruby on Rails

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store