A
A
Anton Ivanov2019-01-08 03:00:31
Ruby on Rails
Anton Ivanov, 2019-01-08 03:00:31

How to specify namepsace in rails routing?

Hello everyone
In rails routing, to ensure api versioning, there is such a construction:

Rails.application.routes.draw do
  concern :versioned_api_methods do
    mount_devise_token_auth_for 'User', at: 'auth', controllers: {
        sessions: 'overrides/sessions',
    }

    resources :users, only: %i[show update]
  end

  namespace :v1 do
    concerns :versioned_api_methods
  end

  namespace :v2 do
    concerns :versioned_api_methods
  end

end

That is, for the users controller, the paths v1/users, v2/users, and so on are obtained. The
question is in the overrides/sessions controller. Is there a way to leave it inside the concern but use versioning?
It is clear that you can put the entire mount_devise_token_auth_for construction into each namespace and manually write v1/overrides/sessions, v2/overrides/sessions and so on, but it may be possible to do this "centrally"?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N. Bekseitov, 2019-01-09
@nbekseitov

Use Constraints

# app/constraints/version_constraint.rb
class VersionConstraint
  def initialize
    @versions = %w[ v1 v2 ]
  end

  def matches?(request)
    @versions.include? request.path_parameters[:version].to_s
  end
end

#routes.rb
scope ':version', constraints: VersionConstraint.new do
  concerns :versioned_api_methods
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question