开发者

Rails - select different view template based on requests

开发者 https://www.devze.com 2023-03-15 22:38 出处:网络
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:

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.fo开发者_开发知识库o.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


You can specify the version number in your routes.rb like:

map.connect '/api/:version/posts', :controller => :api, :action => :index, :version => :version

Then you would have access to the version in your controller via params[:version] and can handle it appropriately.


I think I would suggest making a separate controller for each version, maybe in the same module

Api::VersionOneConroller
Api::VersionTwoConroller

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

class ExampleContrller < ApplicationController 
  after_filter :manage_versions
  ...
end


ApplicationController < ActionController::Base
  protected 
    def manage_versions
      case params[:version]
      when '1.0'
        #response to xml
      when '1.2'
        #response to json
      else 
       # err or default to one
      end
    end
end

something like that could work

read more about filters here http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html

0

精彩评论

暂无评论...
验证码 换一张
取 消