Hi Warren,

Short answer:

The code inside the {}s from this line ("format.xml  { render :xml =>
@posts }") is only executed if the request wants an XML response. The {}s
are common shorthand for passing a block/proc/lambda to a method call and
an alternative to the do/end longhand.

Long answer:

The code you are reading, as far as I know, is something commonly found in
Rails HTTP controllers. Your interpretation of the functionality is
correct: if the request wants HTML, render the HTML template. Otherwise, if
it wants XML, render the "@posts" data as XML. But, this is NOT a Ruby
case/when/then/default statement. Instead, the respond_to method yields a
format object to the block. Once inside the block, the code tells the
format object to perform the default action (render the HTML template) if
the request wants an HTML response. Also, it tells the format object that,
if the request wants an XML response, to execute the given lambda.

So, it seems the confusion is around understanding that the use of
blocks/procs/lambdas gives the respond_to method the ability to only
execute the correct rendering code given to the format object based on what
type of response the request wants.

I hope that is helpful!



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

> As a new comer for ruby, I feel confused for this snippet:
>
>     respond_to do |format|
>       format.html # index.html.erb
>       format.xml  { render :xml => @posts }
>     end
>
> I understand that if format is .html, it will give html response and if
> format is .xml, it will give out xml response.
>
> So this block "do |format| ... end" is case switch like in C++. I have
> difficulty to understand though in ruby, if the user passing .html, as a
> sequential execution (notice in ruby this is not a case switch
> statement), what prevent ruby from executing "format.xml  { render :xml
> => @posts }" line?
>
> To my feeling (though I know I am wrong for sure), these two lines will
> always be executed no matter what kind of format is passed in:
>
>       format.html # index.html.erb
>       format.xml  { render :xml => @posts }
>
> Please help.
>
> --
> Posted via http://www.ruby-forum.com/.
>



-- 
Ryan Cook
720.319.7660