Skip to content
This repository
Browse code

adding controller additions with basic behavior.

  • Loading branch information...
commit 44b36ce2fcff2df819bbe43cb99e5cd3e235ca1a 1 parent c663eff
Ryan Bates authored November 16, 2009
7  lib/cancan.rb
... ...
@@ -1,3 +1,8 @@
1 1
 $:.unshift(File.dirname(__FILE__))
2  
-require 'cancan/ability'
3 2
 require 'cancan/instance_exec'
  3
+require 'cancan/ability'
  4
+require 'cancan/controller_additions'
  5
+
  6
+module CanCan
  7
+  class AccessDenied < StandardError; end
  8
+end
23  lib/cancan/controller_additions.rb
... ...
@@ -0,0 +1,23 @@
  1
+module CanCan
  2
+  module ControllerAdditions
  3
+    def self.included(base)
  4
+      base.helper_method :can?
  5
+    end
  6
+    
  7
+    def unauthorized!
  8
+      raise AccessDenied, "You are unable to access this page."
  9
+    end
  10
+    
  11
+    def current_ability
  12
+      ::Ability.for_user(current_user)
  13
+    end
  14
+    
  15
+    def can?(*args)
  16
+      (@current_ability ||= current_ability).can?(*args)
  17
+    end
  18
+  end
  19
+end
  20
+
  21
+class ActionController::Base
  22
+  include CanCan::ControllerAdditions
  23
+end
32  spec/cancan/controller_additions_spec.rb
... ...
@@ -0,0 +1,32 @@
  1
+require File.dirname(__FILE__) + '/../spec_helper'
  2
+
  3
+class Ability
  4
+  include CanCan::Ability
  5
+end
  6
+
  7
+describe CanCan::ControllerAdditions do
  8
+  before(:each) do
  9
+    @controller_class = Class.new
  10
+    @controller = @controller_class.new
  11
+    mock(@controller_class).helper_method(:can?)
  12
+    @controller_class.send(:include, CanCan::ControllerAdditions)
  13
+  end
  14
+  
  15
+  it "should read from the cache with request uri as key and render that text" do
  16
+    lambda {
  17
+      @controller.unauthorized!
  18
+    }.should raise_error(CanCan::AccessDenied)
  19
+  end
  20
+  
  21
+  it "should have a current_ability method which generates an ability for the current user" do
  22
+    stub(@controller).current_user { :current_user }
  23
+    @controller.current_ability.should be_kind_of(Ability)
  24
+    @controller.current_ability.user.should == :current_user
  25
+  end
  26
+  
  27
+  it "should provide a can? method which goes through the current ability" do
  28
+    stub(@controller).current_user { :current_user }
  29
+    @controller.current_ability.should be_kind_of(Ability)
  30
+    @controller.can?(:foo, :bar).should be_false
  31
+  end
  32
+end

0 notes on commit 44b36ce

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