Both statements are interpreted sequentially as you would expect. But,
let's dissect the second one:

    format.xml { render :xml => @posts }

Here's what we're seeing: call the "xml" method on the "format" object with
a single block parameter containing the code "render :xml => @posts"

The magic here is that the "xml" method is passed a block; a Ruby Proc
object. http://rubydoc.info/stdlib/core/Proc

Since the method is receiving a block/Proc, it can hold onto it for use
later, such as if the Controller determines that the request asked for an
XML response.

See below:

class Printer
  attr_accessor :code

  def initialize(&code)
    @code = code
  end

  def print(string)
    @code.call string
  end
end

my_printer =
  lambda do | string |
    puts string
  end

p = Printer.new &my_printer

puts p.code.inspect

p.print "Ryan"


In this code, I create a block called "my_printer" and pass it to a Printer
object. But, the code inside the block doesn't get executed until I call
the "print" method on my printer object.

Are things getting more clear?


On Fri, Jan 3, 2014 at 4:48 PM, Warren Zhang <lists / ruby-forum.com> wrote:

> Andrew,
>
> Thank you for your explanation. I am vaguely understand what you are
> talking about.
>
> This "magic" rails is doing is most difficult part for me. I found few
> literacy explain rail "magic" well. I am reading "agile web development
> with rail" and rails online documents. They both mentioned that for
> example like
>
>     respond_to do |format|
>       format.html # index.html.erb
>       format.xml  { render :xml => @posts }
>     end
>
> controller will respond to user either html or xml with the right format
> provided by request url. That's it. They don't explain why these two
> statements will not be executed sequentially or anything behind the
> scene. I have big difficult time to understand since I am coming from a
> c++, python world.
>
> How can I accrue my knowledge on this "magic"? Any in depth
> books/documents I can refer to?
>
> --
> Posted via http://www.ruby-forum.com/.
>



-- 
Ryan Cook
720.319.7660