Skip to content

Instantly share code, notes, and snippets.

@devdatta
Forked from ryanb/cancan.rb
Created May 27, 2010 12:59
Show Gist options
  • Save devdatta/415770 to your computer and use it in GitHub Desktop.
Save devdatta/415770 to your computer and use it in GitHub Desktop.
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
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment