Module: Role::UserRoleHelper

Extended by:
ActiveSupport::Concern
Included in:
User
Defined in:
app/models/role/user_role_helper.rb

Overview

Provides the has_role method used to define a number of role helper methods

Instance Method Summary collapse

Instance Method Details

#grant_role(role_name, authorizable = nil) ⇒ Object

Grants a user the role_name, in cases like owner, authorizable should indicate the owned resource


20
21
22
# File 'app/models/role/user_role_helper.rb', line 20

def grant_role(role_name, authorizable = nil)
  roles << Role.find_or_create_by!(name: role_name, authorizable: authorizable)
end

#remove_role(role_name, authorizable = nil) ⇒ Object


24
25
26
27
28
29
30
31
# File 'app/models/role/user_role_helper.rb', line 24

def remove_role(role_name, authorizable = nil)
  # In practice, we only expect to see one role here
  role = roles.named(role_name).authorizing(authorizable)
  return unless role

  roles.destroy(role)
  role.each(&:destroy_if_empty)
end

#role?(role_name, authorizable = nil) ⇒ Boolean

Checks if the user has the role role_name, in cases like owner, authorizable should indicate the owned resource

Returns:

  • (Boolean)

    Returns true if the user has the role


10
11
12
13
14
15
16
# File 'app/models/role/user_role_helper.rb', line 10

def role?(role_name, authorizable = nil)
  if roles.loaded?
    roles.any? { |role| role.name == role_name.to_s && role.authorizes?(authorizable) }
  else
    roles.named(role_name).authorizing(authorizable).exists?
  end
end

#role_namesObject


33
34
35
# File 'app/models/role/user_role_helper.rb', line 33

def role_names
  roles.uniq.pluck(:name)
end