Basically I've developed an app which has two namespaces: admin
, api
and the public one (simply resources :users
for instance). All works fine, however I'm repeating myself quite a bit as some of the controllers in api
for instance could easily be used in admin
.
How can I DRY my code in this case keeping the namespaces?
Thanks!
There are a couple ways I can think of doing it:
(NOT RECOMMENDED) - Send the urls to the same controller in your routes.rb file.
Shared namespace that your controllers inherit from
For example you could have:
# controllers/shared/users_controller.rb
class Shared::UsersController < ApplicationController
def index
@users = User.all
end
end
# controllers/api/users_controller.rb
class Api::UsersController < Shared::UsersController
end
# controllers/admin/users_controller.rb
class Admin::UsersController < Shared::UsersController
end
The above would allow you to share your index action across the relevant controllers. Your routes file in this case would look like this:
# config/routes.rb
namespace :api do
resources :users
end
namespace :admin do
resources :users
end
That's definitely a lot of code to share one action, but the value multiplies as the number of shared actions does, and, most importantly, your code is located in one spot.