respond_to with .text versus .txt

Posted by Luke Francl
on Saturday, September 22

Public service message:

If you’re using ActionController’s respond_to to render a text view of your data, you do it with .text like this:

1
2
3
4
5
6
7
8
9
10
def index
  @foos = Foo.find(:all)

  respond_to do |format|
    format.html
    format.text do
      render :text => @foos.map(&:some_method).join(" ")
    end
  end
end

But the extension you have to use to access the text format depends on your version of Rails.

Rails 1.2.3

In Rails 1.2.3, you must access the text format with the .txt extension because in Rails 1.2.3 only .txt is mapped as an extension for the text/plain MIME type (see mime_type.rb). If you use a .text extension, the browser will return a HTTP 406 error code and nothing will render.

Rails 2.0/Edge Rails

However, it looks like in Rails 2.0, the behavior has been changed and both .text and .txt extensions will work because a facility for extension synonyms has been added (see mime_type.rb and mime_types.rb).

Hopefully teh googles will index this and save somebody else the time it took me to figure out why mine respond_to block wasn’t working!

Comments

Leave a response

  1. JamesSeptember 23, 2007 @ 02:45 PM

    It looks like the Google fairies have blessed me. I was writing a test for my action and I was getting an HTTP 406 error. Here’s my code before:

    
    # I'm using Test/Spec/Rails for my tests
    it "should be able serve plain-text" do
      get :show, :id => @something.id, :format => :text
      status.should.be :success
      # etc...
    end
    
    

    Wrong! This is correct:

    
    # I'm using Test/Spec/Rails for my tests
    it "should be able serve plain-text" do
      get :show, :id => @something.id, :format => 'text'
      status.should.be :success
      # etc...
    end
    
    

    I can’t seem to get the whole ‘text’ and ‘txt’ synonym working in Edge Rails though. Rails just gripes that “Mime::TXT” is an uninitialized constant.

  2. Luke FranclSeptember 23, 2007 @ 07:43 PM

    James—

    Wow, synchronicity! I just posted this yesterday when I was having the same problem. All hail fast Google indexing.

    Are you using format.text in the code?

    Because indeed Mime::TXT is not a registered constant. But you can use .txt for the URL extension, it’s a extension synonym for .text. At least, that’s the way I read the code. I haven’t tried it on Edge Rails yet myself.