Permalink
Browse files

adding can method to Active Record for fetching records matching a sp…

…ecific ability, still needs documentation
  • Loading branch information...
ryanb committed Apr 16, 2010
1 parent baeef0b commit 3c68a911d04641b05a6a037228e08a60c6da317e
Showing with 45 additions and 0 deletions.
  1. +2 −0 CHANGELOG.rdoc
  2. +1 −0 lib/cancan.rb
  3. +20 −0 lib/cancan/active_record_additions.rb
  4. +22 −0 spec/cancan/active_record_additions_spec.rb
View
@@ -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
View
@@ -11,3 +11,4 @@ class Error < StandardError; end
require 'cancan/controller_resource'
require 'cancan/resource_authorization'
require 'cancan/controller_additions'
+require 'cancan/active_record_additions'
@@ -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
@@ -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

0 comments on commit 3c68a91

Please sign in to comment.