public
Last active — forked from ryanb/cancan.rb

  • Download Gist
cancan.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
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 do |comment|
user.role?(:moderator) || (comment && comment.user == user)
end
if user.role? :author
can :create, Article
can :update, Article do |article|
article && article.user == user
end
end
end
end
end
cancan_alternative.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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 do |comment|
comment && comment.user == @user
end
end
def moderator
can :update, Comment
end
def author
can :create, Article
can :update, Article do |article|
article && article.user == @user
end
end
end
declarative_authorization.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
authorization do
role :admin do
has_permission_on [:articles, :comments], :to => [:index, :show, :new, :create, :edit, :update, :destroy]
end
role :guest do
has_permission_on :articles, :to => [:index, :show]
has_permission_on :comments, :to => [:new, :create]
has_permission_on :comments, :to => [:edit, :update] do
if_attribute :user => is { user }
end
end
role :moderator do
includes :guest
has_permission_on :comments, :to => [:edit, :update]
end
role :author do
includes :guest
has_permission_on :articles, :to => [:new, :create]
has_permission_on :articles, :to => [:edit, :update] do
if_attribute :user => is { user }
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.