How can I change the mime type of a request after I receive it?

1.1k Views Asked by At

My customers are sending my rails app requests as either XML or HTML. Under rails 2.10 my controller action had a responds_to block with wants.html and wants.xml. My customers set their HTTP headers for Content-Type=text/xml and Accept=text/xml if they wanted XML and pretty much left off the headers for HTML. Worked great.

Turns out that a large number of my customers had omitted the Accept=text/xml header all along but the respond_to block fired wants.xml as long as they set Content-type=text/xml. At rails3 the respond_to block (correctly) only fires wants.xml if Accept=text/xml is set.

Rather than having many of my customers change their programs, how can I tell rails3 that the request wants XML? I am thinking if I see the Content-Type set to text/xml, I will force the Accept to be text/xml also.

I tried changing the request.env hash directly like this:

class MyController < ApplicationController

def my_xml_or_html_action
  if request.env['CONTENT_TYPE'].to_s.match(/xml/i)
    request.env['HTTP_ACCEPT'] = 'text/xml'
  end
  respond_to do |wants|
    wants.html { redirect_to html_response }
    wants.xml { render xml_response }
  end
end

but that didn't work. I could abandon respond_to completely and do something like:

class MyController < ApplicationController

def my_xml_or_html_action
  if request.env['CONTENT_TYPE'].to_s.match(/xml/i)
    redirect_to html_response
  else
    render xml_response
  end
end

but that seems brute force. Is there a more railsy way to accomplish this?

1

There are 1 best solutions below

0
On

Try:

params[:format] = :xml

Should work.