Skip to content

Instantly share code, notes, and snippets.

@lincank
Created March 7, 2013 15:45
Show Gist options
  • Save lincank/5108957 to your computer and use it in GitHub Desktop.
Save lincank/5108957 to your computer and use it in GitHub Desktop.
A possible good practice for cancan gem
class Ability
include CanCan::Ability
def initialize(user)
@user = user || User.new # new a tmp user for guest
# call corresponding role abilities defined below
@user.roles.each { |role| send(role) }
end
# all possible roles in User model
# user role has all abilities that guest owns, and so on...
def guest
can :read, :all
end
def user
can :manage, Article
end
def admin
can :manage, :all
end
end
# encoding: utf-8
class User < ActiveRecord::Base
# roles for authorization for "cancan" gem, each user can have more than one roles,
# the abilities that this user own, are the union of all roles it has
# ability definition located in models/ability.rb
def roles
roles = ["guest"]
if self.new_record?
return roles
else
roles.append("user")
end
roles.append("admin") if self.is_admin?
roles
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment