How to upgrade to a specific version of the Rails 5 API?

I am developing an application whose backend is written in rails 5 api (beta).

My API will have some versions, and I use this approach to resolve versions:

https://github.com/iamvery/rails-api-example/blob/master/config/routes.rb

Rails.application.routes.draw do
  def api_version(version, &routes)
    api_constraint = ApiConstraint.new(version: version)
    scope(module: "v#{version}", constraints: api_constraint, &routes)
  end

  api_version(1) do
    resources :articles, only: :index
  end

  api_version(2) do
    resources :articles, only: :index
  end
end

The fact is that I do not indicate the version, it shows me an error (obviuos) ( ActionController::RoutingError: No route matches [GET] \...).

But I would like to get directions using the latest api instead of throwing an error.

+4
source share
2 answers

Your route.rb file

Rails.application.routes.draw do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
# Then for a new version create a new scope
end    
end

Create a new api_constraints.rb file in the directory app/lib

class ApiConstraints
  def initialize(options)
    @version = options[:version]
    @default = options[:default]
  end
  def matches?(req)
    @default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}")
  end
end
+2
source

, :

root to: redirect('/api/v2')

, , , - :

@versions = []

def api_version(version)
  @versions << versions
  # The rest of your code..
end

root to: redirect("/v#{@versions.max}")

, .

0

Source: https://habr.com/ru/post/1628650/


All Articles