How to follow DRY principles in different namespaces Rails 4.2?

530 Views Asked by At

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!

1

There are 1 best solutions below

4
On BEST ANSWER

There are a couple ways I can think of doing it:

  1. (NOT RECOMMENDED) - Send the urls to the same controller in your routes.rb file.

  2. 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.