Search code examples
ruby-on-railscontent-type

Rails: how to treat alternative Accept: content-types as JSON?


So far I've found two ways for request.format.json? to be true in Rails (i.e. where the incoming request is treated as JSON). One is if you request a resource and ending in .json the other is if you supply the header Accept: application/json in your request. Each work stand-alone.

I want to register my own "accepts" type for this second case:

Accept: application/vnd.myapp_v1+json and have this treated by rails as a "json request" like application/json, without the need to append .json.

My first thought was to register my own MimeType as :json (within my initialisation code), but this will actually break support for application/json, not what I want to do.

    Mime::Type.register "application/vnd.myapp_v1+json", :json  # my failed attempt

Solution

  • We move iPhone requests over to HTML in our app with a before_filter like so:

    before_filter :determine_format
    
    def determine_format
        request.format = :iphone if (request.env["HTTP_USER_AGENT"] =~ /iPhone/ && request.format == :html)
    end
    

    I imagine you can do something similar with your specific format, maybe like this:

    def determine_format
        request.format = :json if (request.format == 'application/vnd.myapp_v1+json')
    end