From 3c68a911d04641b05a6a037228e08a60c6da317e Mon Sep 17 00:00:00 2001 From: Ryan Bates Date: Thu, 15 Apr 2010 17:04:36 -0700 Subject: [PATCH] adding can method to Active Record for fetching records matching a specific ability, still needs documentation --- CHANGELOG.rdoc | 2 ++ lib/cancan.rb | 1 + lib/cancan/active_record_additions.rb | 20 +++++++++++++++++++ spec/cancan/active_record_additions_spec.rb | 22 +++++++++++++++++++++ 4 files changed, 45 insertions(+) create mode 100644 lib/cancan/active_record_additions.rb create mode 100644 spec/cancan/active_record_additions_spec.rb diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 025a8f0..2bd5161 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,5 +1,7 @@ 1.1.0 (not released) +* Adding "can" method to Active Record for fetching records matching a specific ability + * Adding conditions behavior to Ability#can and fetch with Ability#conditions - see issue #53 * Renaming :class option to :resource for load_and_authorize_resource which now supports a symbol for non models - see issue #45 diff --git a/lib/cancan.rb b/lib/cancan.rb index b39cf93..95ef16e 100644 --- a/lib/cancan.rb +++ b/lib/cancan.rb @@ -11,3 +11,4 @@ require 'cancan/ability' require 'cancan/controller_resource' require 'cancan/resource_authorization' require 'cancan/controller_additions' +require 'cancan/active_record_additions' diff --git a/lib/cancan/active_record_additions.rb b/lib/cancan/active_record_additions.rb new file mode 100644 index 0000000..1bfe9d3 --- /dev/null +++ b/lib/cancan/active_record_additions.rb @@ -0,0 +1,20 @@ +module CanCan + # This module is automatically included into all Active Record. + module ActiveRecordAdditions + module ClassMethods + def can(ability, action) + where(ability.conditions(action, self) || {:id => nil}) + end + end + + def self.included(base) + base.extend ClassMethods + end + end +end + +if defined? ActiveRecord + ActiveRecord::Base.class_eval do + include CanCan::ActiveRecordAdditions + end +end diff --git a/spec/cancan/active_record_additions_spec.rb b/spec/cancan/active_record_additions_spec.rb new file mode 100644 index 0000000..4e4628a --- /dev/null +++ b/spec/cancan/active_record_additions_spec.rb @@ -0,0 +1,22 @@ +require "spec_helper" + +describe CanCan::ActiveRecordAdditions do + before(:each) do + @model_class = Class.new + stub(@model_class).where { :where_stub } + @model_class.send(:include, CanCan::ActiveRecordAdditions) + @ability = Object.new + @ability.extend(CanCan::Ability) + end + + it "should call where(:id => nil) when no ability is defined so no records are found" do + stub(@model_class).where(:id => nil) { :no_where } + @model_class.can(@ability, :read).should == :no_where + end + + it "should call where with matching ability conditions" do + @ability.can :read, @model_class, :foo => 1 + stub(@model_class).where(:foo => 1) { :found_records } + @model_class.can(@ability, :read).should == :found_records + end +end