Basic of Rails Namespaces
The purpose of namespacing is to separate groups of controllers. You can, for example, have a main UsersController for all users and a separate UsersController (with an identical filename) for special classes of users. One possible use might be to separate free-account users from those with a ‘Prime’ subscription.
One of the most common uses of namespacing is to separate administrator functionality. Creating a separate controller under an Admin namespace allows the designer to ensure that only those with a declared admin account can access certain functions.
Namespaces are declared in the Rails routes.rb file using the keyword `namespace`. As in:
namespace :admin do
resources :users
end
In this case we use “:admin” because we’re calling our namespace “Admin”. You could just as easily use “:prime” to use “Prime” as your namespace.
This code tells the program to look for a UsersController inside a folder called “admin” in the “controllers” folder. The file structure would then be
controllers
-admin
-users_controller.rb
The above code declares all the standard routes and CRUD actions for the UsersController. You can declare custom routes or limit the actions expected of the controller. The syntax for this is the same inside the namespace is elsewhere.
1 namespace :admin do
2 get “/dashboard”, to: “users#show”
3 resources :users, only [:index], as: :display
4 end
In this example line 2 creates a path helper “admin_dashboard_path” that translates to “GET admin/dashboard” and goes to a “show” action in “/controllers/admin/users_controller.rb”.
Line 3 creates a path helper “admin_display_index_path” that translates to “GET /admin/users” that goes to an “index” action in “/controllers/admin/users_controller.rb”
When using namespaces it’s also necessary to create separate views. Namespaced controllers will expect their views to be in a similarly named folder inside of “views”. An “index” action in “/admin/users_controller.rb” will by default look for a “/views/admin/index.extension.erb” view. Where ‘extension’ will be ‘html’admin_display_index or whatever format your view should render in.