Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created June 3, 2016 15:44
Show Gist options
  • Save lukeredpath/925039cbe3c3eb499634bd0c76b6bcd7 to your computer and use it in GitHub Desktop.
Save lukeredpath/925039cbe3c3eb499634bd0c76b6bcd7 to your computer and use it in GitHub Desktop.
Defining Pundit policies using role objects
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