Created
September 27, 2012 11:33
-
-
Save higgis/3793544 to your computer and use it in GitHub Desktop.
Rails: Default format using header-based content negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FoosController < ApplicationController | |
respond_to :atom, :api_v1 | |
before_filter :set_default_format | |
def index | |
@foos = Foo.all | |
respond_to do |format| | |
format.xml { render :xml => @foos.to_xml } | |
format.api_v1 { render :json => @foos.to_json } | |
end | |
end | |
protected | |
# why do I need to do this? If I set :defaults => { :format => :xml } | |
# on my route then I only ever get that as the format even if | |
# the client sends an Accept header | |
def set_default_format | |
request.format = :xml if params[:format].nil? && request.headers["HTTP_ACCEPT"].nil? | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mime::Type.register "application/vnd.foos.api.v1+json", :api_v1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyApp::Application.routes.draw do | |
get 'foos', :to => 'foos#index', :as 'foos' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@urbanautomaton Thanks, at least I'm not going mental. Re: the "file extension" thing, is it 1998 all over again or something?