我正在实现一个版本化的 REST API(如 Twitter API),因此根据请求中的版本,我需要呈现特定于该版本的模板,例如,如果客户端请求:
http://www.foo.com/api/v1/posts.json
我想让控制器渲染:
posts/index.v1.json.erb
但如果客户端请求
http://www.foo.com/api/v2/posts.json
我想让控制器渲染:
posts/index.v2。 json.erb
等。
URL中的版本号将被放入route.rb中的params hash中。
我想以可重用的方式执行此操作,因此在特定控制器操作中重复逻辑是不可接受的。
我尝试过查看解析器,但是它无权访问请求,因此我无法将版本号传递给解析器。
有什么办法可以做到这一点吗?
谢谢你!
-小天
I am implementing a REST API which is versioned(like Twitter API), so based on version in request, I need to render template specific to the version, for example, if the client requests:
http://www.foo.com/api/v1/posts.json
I'd like to have the controller render:
posts/index.v1.json.erb
but if the client requests
http://www.foo.com/api/v2/posts.json
I'd like to have the controller render:
posts/index.v2.json.erb
and so on.
the version number in URL will be put in params hash in route.rb.
I want to do this in a reusable way, so it's not acceptable to repeat the logic in specific controller action.
I have tried view resolver, however it doesn't have access to request so there is no way I can pass the version number to resolver.
is there any way to accomplish this?
Thank you!
-Xiaotian
发布评论
评论(2)
您可以在 paths.rb 中指定版本号,如下所示:
然后您可以通过 params[:version] 访问控制器中的版本并可以适当地处理它。
You can specify the version number in your routes.rb like:
Then you would have access to the version in your controller via params[:version] and can handle it appropriately.
我想我建议为每个版本制作一个单独的控制器,也许在同一个模块
或类似的东西中,我不熟悉你的整个应用程序,所以我不能说这是否有效,但这是需要考虑的事情。
------------更新-------------
如果版本差异仅在于输出格式或某些内容,并且所有操作都执行相同的操作,您可以添加在过滤器之后,
类似的东西可以工作,
在这里阅读有关过滤器的更多信息 http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
I think I would suggest making a separate controller for each version, maybe in the same module
or something like that, I am not familiar with your whole app so I cannot say whether that will work, buts its something to consider.
------------update-------------
if the difference in versions in only in output foramtting or somehting, and all the actions do the same thing you could add after filters
something like that could work
read more about filters here http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html