[url=https://github.com/jcasimir/draper]Draper[/url]是一个Ruby gem,它让Rails model方便的应用Decorator模式,解决了传统Rails的两个问题:
[b] 传统Rails Helper一点也不OO,它更像过程式的代码[/b]
Decorator给model对象添加显示相关的职责,比如,你有一个Article对象,Decorator会重载published_at方法,以格式化后的形式输出给view:
[b]将数据格式化相关工作从模型里解放出来[/b]
你一定在model里面写过to_xml或to_json方法。你一定担心过将渲染逻辑放到model里是否合适的问题。或者你一定在某些情况下非常渴望过在model里可以访问current_user方法。你也许遇到过这样的需求:
如果current_user是普通用户你的to_json方法只显示3个属性,如果current_user是adim,to_json方法会显示所有属性。如何在model里处理这样的逻辑?通常会把current_user当作一个参数传到model,这样虽然能解决问题,但看起来却是十分的不舒服。
如果使用Decorate,你就既可以方便的访问helper方法,又可以把与显示相关的职责从model分离出来:
相关资源:
[url=http://rubyeye.herokuapp.com/articles/11]Draper: View Models for Rails[/url]
[url]http://asciicasts.com/episodes/286-draper[/url]
[url]http://blog.steveklabnik.com/2011/09/09/better-ruby-presenters.html[/url]
[url]http://nicksda.apotomo.de/2011/10/rails-misapprehensions-helpers-are-shit/[/url]
[b] 传统Rails Helper一点也不OO,它更像过程式的代码[/b]
Decorator给model对象添加显示相关的职责,比如,你有一个Article对象,Decorator会重载published_at方法,以格式化后的形式输出给view:
class ArticleDecorator < ApplicationDecorator
decorates :article
def published_at
date = h.content_tag(:span, model.published_at.strftime("%A, %B %e").squeeze(" "), :class => 'date')
time = h.content_tag(:span, model.published_at.strftime("%l:%M%p"), :class => 'time').delete(" ")
h.content_tag :span, date + time, :class => 'created_at'
end
end
[b]将数据格式化相关工作从模型里解放出来[/b]
你一定在model里面写过to_xml或to_json方法。你一定担心过将渲染逻辑放到model里是否合适的问题。或者你一定在某些情况下非常渴望过在model里可以访问current_user方法。你也许遇到过这样的需求:
如果current_user是普通用户你的to_json方法只显示3个属性,如果current_user是adim,to_json方法会显示所有属性。如何在model里处理这样的逻辑?通常会把current_user当作一个参数传到model,这样虽然能解决问题,但看起来却是十分的不舒服。
如果使用Decorate,你就既可以方便的访问helper方法,又可以把与显示相关的职责从model分离出来:
class ArticleDecorator < ApplicationDecorator
decorates :article
ADMIN_VISIBLE_ATTRIBUTES = [:title, :body, :author, :status]
PUBLIC_VISIBLE_ATTRIBUTES = [:title, :body]
def to_json
attr_set = h.current_user.admin? ? ADMIN_VISIBLE_ATTRIBUTES : PUBLIC_VISIBLE_ATTRIBUTES
model.to_json(:only => attr_set)
end
end
相关资源:
[url=http://rubyeye.herokuapp.com/articles/11]Draper: View Models for Rails[/url]
[url]http://asciicasts.com/episodes/286-draper[/url]
[url]http://blog.steveklabnik.com/2011/09/09/better-ruby-presenters.html[/url]
[url]http://nicksda.apotomo.de/2011/10/rails-misapprehensions-helpers-are-shit/[/url]