Namespacing Might Be an Architecture

Learn about namespacing in Rails routes for organizing resources and advises against overuse and its role in maintaining clean and efficient code.

We'll cover the following

What is namespacing?

Namespacing in the context of routes is a technique to disambiguate resources that have the same name but are used in completely different contexts. Perhaps our app needs a customer service interface to view, update, and delete widgets, the same resources accessed by users—but requires a totally different UI. While we could complicate WidgetsController and its views to check to see if the user is a customer service agent, it’s often cleaner to create two controllers and two sets of views.

While we could do something like UserWidgetsController and CustomerServiceWidgetsController, it’s cleaner to use namespaces. We can assume WidgetsController is our default view for our users and create a CustomerService namespace so that CustomerService::WidgetsController handles the view of widgets for customer service agents. The namespace method available in config/routes.rb can set this up like so:

Get hands-on with 1200+ tech skills courses.