Question

I have some routes for an API which all have the same defaults (format: :json):

namespace :api do
  namespace :v1 do
    resources :users,    only: [:index, :show, :update],           defaults: { format: :json }
    resources :items,    only: [:index, :show, :update, :destroy], defaults: { format: :json }
    resources :posts,    only: [:index, :show, :update],           defaults: { format: :json }
    resources :comments, only: [:index, :show, :update],           defaults: { format: :json }
    resources :flags,    only: [:index, :show, :update, :create],  defaults: { format: :json }
  end
end

Is there a way to refactor/DRY the code to set the defaults (or even the only) in just one place for only this set of routes? The app also serves HTML at other routes, so it can't be a blanket setting for the whole app.

Was it helpful?

Solution

Move defaults: {format: :json} and the common only options at namespace level. Namespace have them as an option.

 namespace :api, defaults: { format: :json }, only: [:index, :show, :update]  do
  namespace :v1 do
    resources :users  
    resources :items,   only: [:index, :show, :update, :destroy]
    resources :posts
    resources :comments
    resources :flags,    only: [:index, :show, :update, :create]
  end
end

OTHER TIPS

You can use iterator like the following:

[:users, :items, :posts, :comments, :flags].each do |res|
  resources res, only:[...], defaults: {}
end

but I see you have different only so you can also pass it to iterator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top