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 |
But hey, don't worry about the Accept header, it's a vestigial bit of nonsense that will soon be ignored completely in favour of that well-known part of the HTTP spec, "file extension": https://twitter.com/steveklabnik/status/243115995370233856
@urbanautomaton Thanks, at least I'm not going mental. Re: the "file extension" thing, is it 1998 all over again or something?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately Rails' MIME negotiation prioritises the format parameter over everything else, so because it sets a parameter, the defaults hash in the routes file will always win out over an Accept header.
Given this, your existing solution is probably as good as any - the only other option I can think of is to start monkeypatching, which would be grim.