Skip to content

Instantly share code, notes, and snippets.

@rondy rondy/gist:1233857
Created Sep 22, 2011

Embed
What would you like to do?
Authorization (modular abilities)
class User < ActiveRecord::Base
def admin?
role? :admin
end
def role?(role)
roles.include? role
end
end
class Ability
include CanCan::Ability
attr_reader :user
def initialize(user)
@user = user
deny_all! unless @user.admin?
trigger_user_abilities!
end
private
def deny_all!
cannot :manage, :all
end
def trigger_user_abilities!
@user.roles.each do |role|
instance_eval &RoleAbilities.permissions_for_role(role)
end
end
end
module RoleAbilities
def self.permissions_for_role(role)
factory(role).permissions
end
def self.factory(role)
[self.to_s, "#{role}_ability".classify].join("::").constantize
end
class AdminAbility
def self.permissions
lambda do
can :manage, :all
end
end
end
class ModeratorAbility
def self.permissions
lambda do
can [:update, :destroy], Comment
end
end
end
class AuthorAbility
def self.permissions
lambda do
can :create, Post
can :update, Post do |post|
post.user_id == user.id
end
end
end
end
class BasicUserAbility
def self.permissions
lambda do
can :create, Comment
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.