[英]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
...
This is from the Ruby on Rails tutorial: http://edgeguides.rubyonrails.org/getting_started.html#setting-the-application-home-page 这是来自Ruby on Rails教程: http : //edgeguides.rubyonrails.org/getting_started.html#setting-the-application-home-page
respond_to
is a rails specific method that defines how requests for different formats (like xml and html) are responded to. respond_to
是一种特定于rails的方法,用于定义如何响应不同格式(如xml和html)的请求。 The do
and |format|
do
和|format|
delineate a ruby block, with do
acting like a open brace and end
as a closing brace, and |format|
划定一个红宝石块,与do
像个开括号,并end
作为一个右括号,和|format|
defines the block variable that gets its value from the yield
statement within responds_to
. 定义block变量,该变量从responds_to
的yield
语句获取其值。
the "do" is a RUBY block, and the "|format|" “do”是一个RUBY块,而“| 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
respond_to
is a Rails method. respond_to
是一个Rails方法。 do
and the block's parameter ( format
) is standard Ruby. do
和块的参数( format
)是标准的Ruby。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.