Created
November 17, 2009 06:45
-
-
Save ryanb/236709 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ability | |
include CanCan::Ability | |
def initialize(user) | |
user ||= User.new # guest user | |
if user.role? :admin | |
can :manage, :all | |
else | |
can :read, :all | |
can :create, Comment | |
can :update, Comment, :user_id => user.id if user.role?(:moderator) | |
if user.role? :author | |
can :create, Article | |
can :update, Article, :user_id => user.id | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ability | |
include CanCan::Ability | |
def initialize(user) | |
@user = user || User.new # guest user | |
if @user.role? :admin | |
can :manage, :all | |
else | |
guest | |
moderator if @user.role? :moderator | |
author if @user.role? :author | |
end | |
end | |
def guest | |
can :read, :all | |
can :create, Comment | |
can :update, Comment, :user_id => @user.id | |
end | |
def moderator | |
can :update, Comment | |
end | |
def author | |
can :create, Article | |
can :update, Article, :user_id => @user.id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm a bit confused by the following line in the first file:
Perhaps I'm misunderstanding Ruby syntax and operator precedence, but I read that line to say that
can :update, Comment, :user_id => user.id
executes ifuser.role?(:moderator)
returns true and doesn't execute the first half if the second half is false. That means that moderators can only update Comments they created, and nobody else (except for admins) can modify comments, even if they created them. This seems strange and appears to differ from the behavior declared incancan_alternative.rb
anddeclarative_authorization.rb
, which both seem to implement a rule that guests can modify their own comments, and moderators can modify all comments.I suspect the desired one-liner might look like the following (although I haven't tested this):