理解Ruby语法

4

可能的重复问题:
什么是学习Ruby的最佳方法?
解释Ruby on Rails上的迭代器语法

我还在学习Ruby、Ruby on Rails等技术。我越来越能理解所有Ruby和Rails的语法,但其中有一个让我有点困惑。

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @contact_lists }
end

respond_to是一个方法,接受一个过程作为参数。这两种格式看起来也像是方法调用,但我不确定。


1
此外,如果您没有意图返回XML内容,可以删除整个“respond_to do..end”部分。代码将变得更简单。 - Nikita Rybak
3个回答

6

respond_to 是一个接受块的方法。这个块只有一个参数,这里称为 format

现在你在 format 上调用了两个方法。你调用了没有参数的 html 方法和带有块的 xml 方法。

这个块不带参数,并且包含了一个带有哈希作为参数的渲染方法调用。哈希包含键 :xml 和 值 @contact_lists


4

是的,你说得对。

起初,Ruby方法调用有点令人困惑,因为你可以省略括号,并且它们可以接收代码块。

所以,这是解释:

respond_to do |format| 

调用方法respond_to并传递一个块,告诉它如何处理接收到的format

    format.html # index.html.erb

使用名为format的对象调用html方法。
    format.xml  { render :xml => @contact_lists }

方法xml则接收另一个块(do / end 和 { } 是传递块的不同语法)。

end

完成第一个块

请查看此链接另外的回答。


3
我认为这篇文章可以帮助你:这里
另外,请花一分钟阅读respond_to文档。值得注意的是,这个方法在Rails 3中发生了变化

Without web-service support, an action which collects the data for displaying a list of people might look something like this:

def index
  @people = Person.find(:all)
end

Here’s the same action, with web-service support baked in:

def index
  @people = Person.find(:all)

  respond_to do |format|
    format.html
    format.xml { render :xml => @people.to_xml }
  end
end

What that says is, "if the client wants HTML in response to this action, just respond as we would have before, but if the client wants XML, return them the list of people in XML format." (Rails determines the desired response format from the HTTP Accept header submitted by the client.)

Supposing you have an action that adds a new person, optionally creating their company (by name) if it does not already exist, without web-services, it might look like this:

def create
  @company = Company.find_or_create_by_name(params[:company][:name])
  @person  = @company.people.create(params[:person])

  redirect_to(person_list_url)
end

Here’s the same action, with web-service support baked in:

def create
  company  = params[:person].delete(:company)
  @company = Company.find_or_create_by_name(company[:name])
  @person  = @company.people.create(params[:person])

  respond_to do |format|
    format.html { redirect_to(person_list_url) }
    format.js
    format.xml  { render :xml => @person.to_xml(:include => @company) }
  end
end

+1 是为了澄清 Ruby 是如何确定所需的响应格式! - Hector Correa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接