Ruby on Rails Saturday, January 4, 2014

The respond_to is a Ruby block statement
respond_to do |format| creates the variable format and calls html or xml on it

so for each format, carry out some action. In this case, respond to the http request with the appropriate format(html, xml, json)
respond_to do |format|
  format.html
  format.xml
end

its like iterating using the each do structure. For each post, carry out some action
@posts.each do |post|
   post.title
   post.body
 end

I suggest you lookup/read about Ruby blocks

On Friday, January 3, 2014 3:26:20 PM UTC-5, Ruby-Forum.com User 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/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/20121b21-7359-4e58-beb2-1b6d06552eef%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment