Draper: View Models for Rails

25 篇文章 0 订阅
1 篇文章 0 订阅
[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:


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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值