views:

46

answers:

2

Hi all,

I wanted to know if there are any way to change the view format for based on domain name the same rails app.

For example :

  • www.domain.com => respond_to format.html
  • api.domain.com => respond_to format.xml or format.json

Thanks all for your help

+3  A: 

Yes, use a before_filter in your controller and set the response.format according to the value of request.host.

class Controller < ActionController::Base

  before_filter :adapt_response_format

  protected

    def adapt_response_format
      response.format = case request.host
        when "xml.foo.com" then :xml
        else                    :html
    end

end
Simone Carletti
Awesome !Thanks you very much !
jjmartres
A: 

Here is an alternative approach to what I am guessing is your problem.

Why not ask your clients to set the Accept header to application/xml or application/json depending on what format they want? You can serve html by default to support web browsers.

This way you don't need to have two different hosts.

Darrel Miller
content negotiation?! are you mad, Darrell!? I jest, I jest. ;)
Mike
@Mike I know, it seems crazy to do use HTTP features for what they were intended.
Darrel Miller