Reputation: 542
I have a bunch of resources that I want to make available at both /api/[PATH]
and /api/v1/[PATH]
. In other words, both /api/tasks/12
and /api/v1/tasks/12
should be routed to Api::V1::TasksController#show
. However, for reasons of backward-compatibility I don't want to use external redirects - all the routing should happen internally.
This is the best I've found so far, but it requires replicating the resource
declarations:
namespace :api, defaults: {format: :json} do
namespace :v1, as: 'v1' do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
scope module: 'v1' do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
end
Yes, I could put them in a Proc if I really wanted to avoid duplication, but that just seems ridiculous.
I tried something like match '*path', path: '/v1', via: :all
(inside the first namespace
) but that didn't seem to work.
Surely there's a better way of doing this?
Upvotes: 3
Views: 597
Reputation: 76774
Routes
I understand your question - you want the same routes (including controllers) to be defined for the /v1
API as the standard /api
.
The best I can give is to help you define some routing concerns:
#config/routes.rb
concern :api do
resource :profile, only: [:show]
resources :notifications, only: [:create]
resources :tasks, only: [:index, :create, :show, :update]
end
namespace :api, defaults: {format: :json} do
scope module: "v1" do
concerns :api
end
namespace :v1, as: 'v1' do
concerns: :api
end
end
I know it's a bit WET, but it's the surest way to achieve what you're looking for
Upvotes: 3