문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top