From 12b0bff0b62b4bebb620fefad6f02c9d92d5b1e2 Mon Sep 17 00:00:00 2001 From: Mani Tadayon Date: Wed, 5 Jan 2011 23:12:59 -0800 Subject: [PATCH] Use `Mongoid::Matchers#matches?` instead of a database query in `MongoidAdapter#matches_conditions_hash?` --- lib/cancan/model_adapters/mongoid_adapter.rb | 4 +++- spec/cancan/model_adapters/mongoid_adapter_spec.rb | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/cancan/model_adapters/mongoid_adapter.rb b/lib/cancan/model_adapters/mongoid_adapter.rb index 19b8e45..70e39e2 100644 --- a/lib/cancan/model_adapters/mongoid_adapter.rb +++ b/lib/cancan/model_adapters/mongoid_adapter.rb @@ -10,7 +10,9 @@ module CanCan end def self.matches_conditions_hash?(subject, conditions) - subject.class.where(conditions).include?(subject) # TODO don't use a database query here for performance and other instances + # To avoid hitting the db, retrieve the raw Mongo selector from + # the Mongoid Criteria and use Mongoid::Matchers#matches? + subject.matches?( subject.class.where(conditions).selector ) end def database_records diff --git a/spec/cancan/model_adapters/mongoid_adapter_spec.rb b/spec/cancan/model_adapters/mongoid_adapter_spec.rb index 61b96ef..bab6665 100644 --- a/spec/cancan/model_adapters/mongoid_adapter_spec.rb +++ b/spec/cancan/model_adapters/mongoid_adapter_spec.rb @@ -84,7 +84,7 @@ if ENV["MODEL_ADAPTER"] == "mongoid" it "Calls where on the model class when there are criteria" do obj = MongoidProject.create(:title => 'Bird') @conditions = {:title.nin => ["Fork", "Spoon"]} - mock(MongoidProject).where(@conditions) {[obj]} + @ability.can :read, MongoidProject, @conditions @ability.should be_able_to(:read, obj) end