动态组合named_scope
by Robin Lu on Apr.22, 2009, about plugin, rubyonrails
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
April 23rd, 2009 on 4:37 pm
这个功能rails 2.3不是提供了吗?“ dynamic scope”.
Article.scoped_by_published(true).scoped_by_user_id(1)
April 23rd, 2009 on 6:53 pm
dynamic scope是动态生成named scope。
这个是动态组合named scope。两回事。
June 17th, 2009 on 10:20 pm
searchlogic 可以动态组合named scope
http://github.com/binarylogic/searchlogic/tree/master
User.username_like(”bjohnson”).age_greater_than(20).ascend_by_username
search = User.search
search.username_like
search.age_gt = 2
search.id_gt(10).email_begins_with(”bjohnson”)
search.all