From da663aaed10439d9844cbcf917cf8cec10690844 Mon Sep 17 00:00:00 2001 From: Anuj Dutta Date: Sun, 10 Jun 2012 22:54:45 +0100 Subject: [PATCH] Fix for issue-644 to allow users to specify a mix of can and cannot rules with mongo. --- lib/cancan/model_adapters/mongoid_adapter.rb | 3 ++- .../cancan/model_adapters/mongoid_adapter_spec.rb | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/lib/cancan/model_adapters/mongoid_adapter.rb b/lib/cancan/model_adapters/mongoid_adapter.rb index 7993252..6c7f37d 100644 --- a/lib/cancan/model_adapters/mongoid_adapter.rb +++ b/lib/cancan/model_adapters/mongoid_adapter.rb @@ -30,8 +30,9 @@ module CanCan else # we only need to process can rules if # there are no rules with empty conditions - rules = @rules.reject { |rule| rule.conditions.empty? } + rules = @rules.reject { |rule| rule.conditions.empty? && rule.base_behavior } process_can_rules = @rules.count == rules.count + rules.inject(@model_class.all) do |records, rule| if process_can_rules && rule.base_behavior records.or rule.conditions diff --git a/spec/cancan/model_adapters/mongoid_adapter_spec.rb b/spec/cancan/model_adapters/mongoid_adapter_spec.rb index fc53d23..81ce4a6 100644 --- a/spec/cancan/model_adapters/mongoid_adapter_spec.rb +++ b/spec/cancan/model_adapters/mongoid_adapter_spec.rb @@ -73,6 +73,17 @@ if ENV["MODEL_ADAPTER"] == "mongoid" MongoidProject.accessible_by(@ability, :read).entries.should == [sir] end + it "should return the correct records when a mix of can and cannot rules in defined ability" do + @ability.can :manage, MongoidProject, :title => 'Sir' + @ability.cannot :destroy, MongoidProject + + sir = MongoidProject.create(:title => 'Sir') + lord = MongoidProject.create(:title => 'Lord') + dude = MongoidProject.create(:title => 'Dude') + + MongoidProject.accessible_by(@ability, :destroy).entries.should == [sir] + end + it "should be able to mix empty conditions and hashes" do @ability.can :read, MongoidProject @ability.can :read, MongoidProject, :title => 'Sir' @@ -185,7 +196,7 @@ if ENV["MODEL_ADAPTER"] == "mongoid" @ability.can :read, MongoidProject, :foo => {:bar => 1} MongoidProject.accessible_by(@ability, :read).entries.first.should == obj end - + it "should exclude from the result if set to cannot" do obj = MongoidProject.create(:bar => 1) obj2 = MongoidProject.create(:bar => 2) @@ -202,7 +213,7 @@ if ENV["MODEL_ADAPTER"] == "mongoid" @ability.can :read, MongoidProject, :bar => 2 MongoidProject.accessible_by(@ability, :read).entries.should =~ [obj, obj2] end - + it "should not allow to fetch records when ability with just block present" do @ability.can :read, MongoidProject do false