Created
June 3, 2016 15:44
-
-
Save lukeredpath/925039cbe3c3eb499634bd0c76b6bcd7 to your computer and use it in GitHub Desktop.
Defining Pundit policies using role objects
This file contains hidden or 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 Role | |
def can?(ability) | |
ability_query = "can_#{ability}?" | |
respond_to?(ability_query) ? __send__(ability_query) : false | |
end | |
end | |
class ManagerRole < Role | |
def can_manage_users? | |
true | |
end | |
end | |
class StaffRole < Role | |
def can_manage_users? | |
false | |
end | |
end | |
class User | |
def roles | |
[ManagerRole.new, StaffRole.new] | |
end | |
def can?(ability) | |
roles.any? { |r| r.can?(ability) } | |
end | |
end | |
class UserPolicy < ApplicationPolicy | |
def create? | |
user.can?(:manage_users) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment