From: Andrew Timberlake Date: 2008-01-18T02:34:43+09:00 Subject: Re: Ruby syntax in "respond_to do |format| line -- can clarify? > I'm new to both Ruby and Rails (I come from an ASP.NET/C# background, > mainly, and I also have done a fair amount of PHP). I'm looking at > these lines from my controller: > > respond_to do |format| > format.html # index.html.erb > format.xml { render :xml => @posts } > end > > And I just can't quite get my head around it completely. I know the end > result is that it renders different types of output. But I don't > understand how it's executing. I read the docs here: > http://www.cs.auckland.ac.nz/references/ruby/doc_bundle/Manual/man-1.4/syntax.html > > But I still don't understand where |format| is coming from, or what it's > doing. From what I've seen in Ruby, I think of something like |format| > as being part of a foreach type block. As in "possible_formats.each do > |format|". > > So this is what I'm seeing in my head when I look at that block: > > for(format in ????) > respond_to(format.html) # index.html.erb will be rendered by default > respond_to(format.xml , { render :xml => @posts }) > end > > But that can't be right, because there's nothing for ???? to be resolved > to... > > Can someone help clear this up for me? Joshua respond_to is the method, it provides the block with the format object. Within the block, you are calling the methods html and xml on the format object supplied. Rather than a loop, the block is more like a callback function that accepts a format object as a parameter. The format object now understands that it can respond with either html or xml output. Rails then uses the Accepts header of the calling client (browser etc) to decide which of the formats to return. You can also append .html or .xml to the url to force one or the other format. Hope that helps Andrew Timberlake andrew@andrewtimberlake.com 082 415 8283 skype: andrewtimberlake "I have never let my schooling interfere with my education." --Mark Twain