Look at all the references to merchant and merchants! Lets count: Twenty-Four uses of the word! Dang! And this is in JUST the endpoints related to merchants! This same replication exists in our items, customers, invoices, and more.

It’s also clunky to read. Every single merchants controller in the collection starts the same. That lowers the ratio of signal to noise, as a developer. No good.

Hopefully someone moving through Turing behind us will take this chance for a really easy fix.

I moved the merchants_controllerup one level, to be outside of the merchants folder, and then everywhere else, I can infer that if a controller is in merchants/, it is related to the merchants class. (Rocket science!)

That looks a lot better. Half the number of references to merchants in the routes. Now… this requires renaming all the controllers, etc, so lets make that happen and see if our tests still pass.

We’ll have to update a few files for each of these changes:

routes.rb

the associated controller (fixing the class name of the controller)

The associated view, since the expected path is determined by the controller class name.

So, swap everything around, and all the tests still pass, and our routes are way more readable:

Update

So someone suggested a way to refactor even more.

What’s that? A chance for even more refactoring?

I’ll take it. Back to routes.rb

I immediately was able to get down to replying on Rails “convention over configuration”, which basically means Rails is going to look in specific places for specific things. Like in the /controllers/api/v1/merchants/ directory for most of my merchants controllers.

Interesting. It dropped the /merchants/ from the endpoint path. That is not what I expected, especially because it is still nested under merchants in my routes file. Hm.

Well, on further investigation, looks like the PendingCustomersController didn’t even need to be nested inside of /merchants. It relies on a parameter passed into it (the merchant ID) but the routes that we told it to live at doesn’t require a merchant object in the path.

Rejigger some of the folder names and locations, and everything still passes.

This was a really good thing for me to learn about how Rails assumes controllers and views should be organized. It feels better to not override it’s default behavior, or to be verbose in describing where controllers should go.