石锅拌饭

动态组合named_scope

by Robin Lu on Apr.22, 2009, about ,

named_scope是Ruby On Rails 2.x后一个非常好用的功能,介绍的地方已经很多,在这里不再多说。

named_scope有一个很好的地方,是数个scope和scope可以组合,本来很难看的代码可以变成这样优美可读的形式:

Post.published.by_author(user).within_a_week.in_forum(forum)

但有时候,到底需要将哪些scopes组合在一起,在运行时才能决定,没法在程序中写死。找了一下,似乎没有现成的解决方案,就写了一个叫ScopeGroup的plugin。

使用这个plugin,可以在运行时动态组合named scope,然后可以针对这个组合来调用find, count, average等等函数。
比如,如下代码:

# 为model Post创建一个ScopeGroup
scope_group = ScopeGroup.new(Post)
# 将scope分别加入组合
scope_group.published
scope_group.by_author(user)
scope_group.within_a_week

再调用

scope_group.find(:all)

就等同于:

Post.published.by_author(user).within_a_week

我们碰到的一个用户场景是需要根据地区、类别、状态等各种条件分层次组合生成报表,使用了动态组合named scope的方式,大大简化了代码。

我把这个插件放在了github: ScopeGroup项目主页链接

安装方式:

script/plugin install git://github.com/robin/scopegroup.git
:,

3 Comments for this entry

Search

Archives

Browse by tags

agile apple blog book design ecto extension firefox git google hack ichm iphone keyword life mac madfox movie nonsense opensource plugin pm ruby rubyonrails sns software startup wordpress work 财帮子