4. with_scopeの例
User.find(:all)
# SELECT * FROM users
User.find(:all, :conditions=>[“deleted=?”,false])
# SELECT * FROM users WHERE deleted = 0
User.with_scope(
:find=>{:conditions=>[“deleted=?”,false]}) do
User.find(:all)
end
# SELECT * FROM users WHERE deleted = 0
11. 有効なユーザ
class User < ActiveRecord::Base
named_scope(:active,
{:condition=>["deleted = ?", false]})
end
describe “activeなユーザ” do
it “は全員削除されて*いない*こと” do
User.active.should be_all{|u| not u.deleted }
end
end
13. 人気のあるユーザ
実行時にscopeの一部を指定
class User < ActiveRecord::Base
named_scope :active,
:condition=>["deleted = ?", false]
named_scope :hot,
Proc.new{|arg|
{:conditions=>[“popularity > ?”, arg],
:order =>"popularity DESC"}
}
end
14. 人気のあるユーザ
実行時にscopeの一部を指定
describe “人気度80以上のユーザ” do
before do
@users = User.hot(80)
end
it "のうちトップはdahliaであること" do
@users.first.should == users(:dahlia)
end
end
16. 人気かつ有効なユーザ
crossover 2 scopes
describe "BAN! dahlia" do
before(:each) do
# dahliaの削除フラグを立てる つまり active usersの集合から外す
users(:dahlia).update_attribute(:deleted, true)
end
it "アクティブユーザで最も人気なのはcharlesであること" do
User.active.hot(80).first.should == users(:charles)
end
it "クエリ発行(select_all)は一回だけ呼ばれること" do
User.connection.should_receive(:select_all).once.and_return([])
User.hot(80).active.find(:all)
end
end
21. Scope#method_missing
def method_missing(method, *args, &block)
if scopes.include?(method)
scopes[method].call(self, *args)
else
with_scope :find => proxy_options do
proxy_scope.send(method, *args, &block)
end
end
end
24. Scope#method_missing
def method_missing(method, *args, &block)
if scopes.include?(method)
scopes[method].call(self, *args)
else
with_scope :find => proxy_options do
proxy_scope.send(method, *args, &block)
end
end
end
25. 飞颈迟丑冲蝉肠辞辫别で
書き直したイメージ
User.with_scope(
:find=>{:conditions=>[”popularity>?”, 80],
:order=>”popularity” }) do
User.with_scope(
:find=>{:conditons=>[“deleted=?”, false]}) do
User.find(:all).each{ ... }
end
end Rails2.xではこのままでは動きません