Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Default to Canable::Transgression when the current_user is nil.

  • Loading branch information...
commit c93ee06b302370121a34fb71dc9e35df62914518 1 parent 36faf97
@jopotts jopotts authored
Showing with 31 additions and 4 deletions.
  1. +22 −0 README.rdoc
  2. +1 −1  lib/canable.rb
  3. +8 −3 test/test_enforcers.rb
View
22 README.rdoc
@@ -103,6 +103,28 @@ You can add your own actions like this:
The first parameter is the can method (ie: can_publish?) and the second is the able method (ie: publishable_by?).
+Ables can also be added as class methods. For example, to restrict access to an index action:
+
+ Canable.add(:index, :indexable)
+
+Then enforce by passing the class instead of the instance:
+
+ class ArticlesController < ApplicationController
+ def index
+ @articles = Article.all
+ enforce_index_permission(Article)
+ end
+ end
+
+Then in the article model, add the able check as a class method:
+
+ class Article
+ ...
+ def self.indexable_by?(user)
+ !user.nil?
+ end
+ end
+
== Review
So, lets review: cans go on user model, ables go on everything, you override ables in each model where you want to enforce permissions, and enforcers go after each time you find or initialize an object in a controller. Bing, bang, boom.
View
2  lib/canable.rb
@@ -67,7 +67,7 @@ def #{able}_by?(user)
def self.add_enforcer_method(can)
Enforcers.module_eval <<-EOM
def can_#{can}?(resource)
- current_user.can_#{can}?(resource)
+ current_user && current_user.can_#{can}?(resource)
end
def enforce_#{can}_permission(resource, message="")
View
11 test/test_enforcers.rb
@@ -9,7 +9,7 @@ class EnforcersTest < Test::Unit::TestCase
# Overriding example
def can_update?(resource)
- return false if current_user.nil?
+ return false if current_user && current_user.banned?
super
end
@@ -42,9 +42,14 @@ def edit
@user.expects(:can_view?).with(@article).returns(false)
assert_raises(Canable::Transgression) { @controller.show }
end
-
- should "be able to override can_xx? method" do
+
+ should "raise error whenever current_user nil" do
@controller.current_user = nil
+ assert_raises(Canable::Transgression) { @controller.show }
+ end
+
+ should "be able to override can_xx? method" do
+ @user.expects(:banned?).returns(true)
assert_raises(Canable::Transgression) { @controller.update }
end
Please sign in to comment.
Something went wrong with that request. Please try again.