Edge Rails 的更新:render全面提升70%

Posted by yudi
on Saturday, December 22

我们在开发的时候都喜欢用最少的代码实现最多的功能。

从这个角度来讲,render call 又向前迈进了一步。第一个功能则是在 render call 里设置 Location header 的值。 这个新特性通常在建立 RESTful 服务时被使用 ── 当一个实体被建立后,这个实体的URI需要被寄回 Location response header:

1
2
3
4
5
@contact = Contact.create(params[:contact])
respond_to do |wants|
  wants.xml { render :xml => @contact.to_xml, :status => :created,
                     :location => contact_url(@contact) }
end

在这以前,您首先需要亲自设定 Location header:


response.headers["Location"] = contact_url(@contact)

让我们在压缩一下 render 一行代码:不觉得 to_xml 转换显得有些繁琐吗? 我是说,我们早已经告诉它去渲染 :xml,它也应当明白如何将model 渲染为 xml。好歹,它现在明白怎么做了:


render :xml => @contact, :status => :created, :location => contact_url(@contact)

看到我们不必在那里再使用 to_xml 了吧?如果您的model 支持 to_xml (所有的ActiveRecord下的model都会),render :xml 将自动将它渲染到 xml。好哇,这下子可以少敲7个字母了!

原文作者是 Ryan Daigle, 请访问他的博客
本片译文的原文地址:http://ryandaigle.com/articles/2007/4/25/what-s-new-in-edge-rails-render-now-70-more-betterer

Comments

Leave a response