Created
March 7, 2013 15:45
-
-
Save lincank/5108957 to your computer and use it in GitHub Desktop.
A possible good practice for cancan gem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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