Permalink
Browse files

Merge branch 'master' of https://github.com/jopotts/canable into jopo…

…tts-master
  • Loading branch information...
2 parents 8dd4f01 + c93ee06 commit b32d5005d692c5c677836f5276b5ba79357bd788 @jnunemaker committed Sep 7, 2011
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
@@ -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
@@ -65,7 +65,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="")
@@ -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

0 comments on commit b32d500

Please sign in to comment.