Skip to content
This repository
Browse code

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

…ecific ability, still needs documentation
  • Loading branch information...
commit 3c68a911d04641b05a6a037228e08a60c6da317e 1 parent baeef0b
Ryan Bates authored April 15, 2010
2  CHANGELOG.rdoc
Source Rendered
... ...
@@ -1,5 +1,7 @@
1 1
 1.1.0 (not released)
2 2
 
  3
+* Adding "can" method to Active Record for fetching records matching a specific ability
  4
+
3 5
 * Adding conditions behavior to Ability#can and fetch with Ability#conditions - see issue #53
4 6
 
5 7
 * Renaming :class option to :resource for load_and_authorize_resource which now supports a symbol for non models - see issue #45
1  lib/cancan.rb
@@ -11,3 +11,4 @@ class Error < StandardError; end
11 11
 require 'cancan/controller_resource'
12 12
 require 'cancan/resource_authorization'
13 13
 require 'cancan/controller_additions'
  14
+require 'cancan/active_record_additions'
20  lib/cancan/active_record_additions.rb
... ...
@@ -0,0 +1,20 @@
  1
+module CanCan
  2
+  # This module is automatically included into all Active Record.
  3
+  module ActiveRecordAdditions
  4
+    module ClassMethods
  5
+      def can(ability, action)
  6
+        where(ability.conditions(action, self) || {:id => nil})
  7
+      end
  8
+    end
  9
+    
  10
+    def self.included(base)
  11
+      base.extend ClassMethods
  12
+    end
  13
+  end
  14
+end
  15
+
  16
+if defined? ActiveRecord
  17
+  ActiveRecord::Base.class_eval do
  18
+    include CanCan::ActiveRecordAdditions
  19
+  end
  20
+end
22  spec/cancan/active_record_additions_spec.rb
... ...
@@ -0,0 +1,22 @@
  1
+require "spec_helper"
  2
+
  3
+describe CanCan::ActiveRecordAdditions do
  4
+  before(:each) do
  5
+    @model_class = Class.new
  6
+    stub(@model_class).where { :where_stub }
  7
+    @model_class.send(:include, CanCan::ActiveRecordAdditions)
  8
+    @ability = Object.new
  9
+    @ability.extend(CanCan::Ability)
  10
+  end
  11
+  
  12
+  it "should call where(:id => nil) when no ability is defined so no records are found" do
  13
+    stub(@model_class).where(:id => nil) { :no_where }
  14
+    @model_class.can(@ability, :read).should == :no_where
  15
+  end
  16
+  
  17
+  it "should call where with matching ability conditions" do
  18
+    @ability.can :read, @model_class, :foo => 1
  19
+    stub(@model_class).where(:foo => 1) { :found_records }
  20
+    @model_class.can(@ability, :read).should == :found_records
  21
+  end
  22
+end

0 notes on commit 3c68a91

Please sign in to comment.
Something went wrong with that request. Please try again.