Skip to content

Instantly share code, notes, and snippets.

@rondy
Created September 22, 2011 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondy/1233857 to your computer and use it in GitHub Desktop.
Save rondy/1233857 to your computer and use it in GitHub Desktop.
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