Created
December 14, 2014 12:58
-
-
Save stabenfeldt/3cb096457cb637f18448 to your computer and use it in GitHub Desktop.
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
# | |
# Basically following the role based authorization approach explained by | |
# https://github.com/ryanb/cancan/wiki/Role-Based-Authorization | |
# | |
module User::Role | |
extend ActiveSupport::Concern | |
ROLES = [:user, :admin] | |
DEFAULT = :user | |
included do | |
before_save :default_role | |
end | |
def roles=(roles) | |
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+) | |
end | |
def roles | |
ROLES.reject do |r| | |
( (roles_mask || 0) & 2**ROLES.index(r) ).zero? | |
end | |
end | |
def is?(role) | |
roles.include? role.to_sym | |
end | |
private | |
def default_role | |
self.roles = [DEFAULT] if self.roles.blank? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment