Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "respond_to" and "do" and "|format|" in this Rails code?

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end
...
  • What exactly is "respond_to" Is it part of rails?
  • What is "do" and"|format|"? Why are there vertical separators around format?
  • How come Rails knows about the Post model? I didn't import that model. (In Python/Django, you have to import a model before you can use it)

This is from the Ruby on Rails tutorial: http://edgeguides.rubyonrails.org/getting_started.html#setting-the-application-home-page

like image 720
TIMEX Avatar asked Aug 22 '10 23:08

TIMEX


2 Answers

respond_to is a rails specific method that defines how requests for different formats (like xml and html) are responded to. The do and |format| delineate a ruby block, with do acting like a open brace and end as a closing brace, and |format| defines the block variable that gets its value from the yield statement within responds_to.

like image 193
ennuikiller Avatar answered Sep 28 '22 16:09

ennuikiller


the "do" is a RUBY block, and the "|format|" could be anything, its just a variable to use inside that block, here is another example:

respond_to do |x|
  x.html # index.html.erb
  x.xml  { render :xml => @posts }
end
like image 31
Brian Joseph Spinos Avatar answered Sep 28 '22 17:09

Brian Joseph Spinos