I'm developing an application which backend is being written in rails 5 api (beta version).
My API will have some versions, and I'm using this approach to address versioning:
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
问题是当我没有指定版本时,它会向我显示(obviuos)错误(ActionController::RoutingError: No route matches [GET] \...
)。
但我想使用最新的api版本路由而不是抛出错误。
答案 0 :(得分:4)
您的routes.rb文件
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
目录中创建新的api_constraints.rb文件
private String url;
@Factory(dataProvider = "urls", dataProviderClass = URLProvider.class)
public EndToEndTest(String url) {
this.url = url;
}
答案 1 :(得分:0)
我会添加一个根路由,并使用一个简单的重定向,如下所示:
root to: redirect('/api/v2')
我相信这可以通过一些更改来动态完成,如下所示:
@versions = []
def api_version(version)
@versions << versions
# The rest of your code..
end
root to: redirect("/v#{@versions.max}")
我希望这会有所帮助。