Skip to content

Instantly share code, notes, and snippets.

@stabenfeldt
Created December 14, 2014 12:58
Show Gist options
  • Save stabenfeldt/3cb096457cb637f18448 to your computer and use it in GitHub Desktop.
Save stabenfeldt/3cb096457cb637f18448 to your computer and use it in GitHub Desktop.
#
# 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