From dbcd93e095bc8b06f30b080adb37becbce617246 Mon Sep 17 00:00:00 2001 From: Mani Tadayon Date: Thu, 14 Oct 2010 18:21:59 -0700 Subject: [PATCH] Fix bug with Mongoid document where :manage :all caused accessible_by to return nothing and add specs to test for :manage :all. --- lib/cancan/mongoid_additions.rb | 22 ++++++++++++---------- spec/cancan/mongoid_additions_spec.rb | 12 +++++++++++- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/lib/cancan/mongoid_additions.rb b/lib/cancan/mongoid_additions.rb index c49aa90..5c05044 100644 --- a/lib/cancan/mongoid_additions.rb +++ b/lib/cancan/mongoid_additions.rb @@ -22,7 +22,16 @@ module CanCan end def conditions - @can_definitions.first.instance_variable_get(:@conditions) + if @can_definitions.size == 0 + false_query + else + @can_definitions.first.instance_variable_get(:@conditions) + end + end + + def false_query + # this query is sure to return no results + {:_id => {'$exists' => false, '$type' => 7}} # type 7 is an ObjectID (default for _id) end end @@ -81,16 +90,9 @@ module CanCan # # Here only the articles which the user can update are returned. This # internally uses Ability#conditions method, see that for more information. - def accessible_by(ability, action = :read) + def accessible_by(ability, action = :read) query = ability.query(action, self) - - if query.conditions.blank? - # this query is sure to return no results - # we need this so there is a Mongoid::Criteria object to return, since an empty array would cause problems - where({:_id => {'$exists' => false, '$type' => 7}}) # type 7 is an ObjectID (default for _id) - else - where(query.conditions) - end + where(query.conditions) end end diff --git a/spec/cancan/mongoid_additions_spec.rb b/spec/cancan/mongoid_additions_spec.rb index 5259567..d078c99 100644 --- a/spec/cancan/mongoid_additions_spec.rb +++ b/spec/cancan/mongoid_additions_spec.rb @@ -55,7 +55,7 @@ describe CanCan::MongoidAdditions do @model_class.create :title => 'Lord' @model_class.create :title => 'Dude' - @model_class.accessible_by(@ability, :read).should == [] + @model_class.accessible_by(@ability, :read).entries.should == [] end it "should return the correct records based on the defined ability" do @@ -66,6 +66,16 @@ describe CanCan::MongoidAdditions do @model_class.accessible_by(@ability, :read).should == [sir] end + + it "should return everything when the defined ability is manage all" do + @ability.can :manage, :all + sir = @model_class.create :title => 'Sir' + lord = @model_class.create :title => 'Lord' + dude = @model_class.create :title => 'Dude' + + @model_class.accessible_by(@ability, :read).entries.should == [sir, lord, dude] + end + describe "Mongoid::Criteria where clause Symbol extensions using MongoDB expressions" do it "should handle :field.in" do