Topic: Why does this respond_to block work?

Hello,
  I've been reading quite a bit about Rails 1.2 lately and many of the examples contain some ruby code that is beyond me.

respond_to do |wants|
  wants.html
  wants.xml {render :xml => @people.to_xml}
end

After looking at the API for respond_to, I'm still not sure what sort of object (wants) respond_to is injecting into this block, nor what the .html and .xml methods do.  It seems to me that this controller would return BOTH the html and xml representations.

Please help me get my thick head around this!

Re: Why does this respond_to block work?

respond_to has actually been around since 1.1, but it seems to be receiving more publicity lately.

The "wants" variable in this case is of class Responder which, as I understand it, just keeps track of what formats the action can return. Don't think of it as returning both html and xml, but instead think of it as listing what different representations this action can return. The Responder will only choose one from the list to use.

How it chooses which format to use is dependent upon the Accepts HTTP header in the request. In 1.2 you can also specify which type of response you want through an extension. If no specification is given, the first format in the list will be chosen (in this case HTML).

Since no block is given for HTML, it will just perform the normal operation, which is render the rhtml template.

Railscasts - Free Ruby on Rails Screencasts