1
0
Fork 0
This repository has been archived on 2023-03-27. You can view files and clone it, but cannot push or open issues or pull requests.
lpr-partynest/app/models/role.rb

60 lines
1.2 KiB
Ruby
Raw Normal View History

2018-11-29 18:26:48 -05:00
# frozen_string_literal: true
class Role < ApplicationRecord
2019-02-01 16:01:02 -05:00
NAMES = %w[
superuser
].map(&:freeze).freeze
2019-03-25 20:56:31 -04:00
scopify
################
# Associations #
################
2019-02-01 23:18:22 -05:00
has_many :account_roles,
2019-02-01 23:35:08 -05:00
-> { active },
2019-02-01 23:27:42 -05:00
inverse_of: :role,
2019-04-28 09:34:46 -04:00
dependent: :restrict_with_exception
2019-02-01 22:48:23 -05:00
has_many :accounts, through: :account_roles
2018-11-29 18:26:48 -05:00
belongs_to :resource, polymorphic: true, optional: true
2019-03-25 20:56:31 -04:00
###############
# Validations #
###############
2019-02-01 16:01:02 -05:00
validates :name,
2019-04-28 09:34:46 -04:00
presence: true,
2019-02-01 16:01:02 -05:00
inclusion: { in: NAMES }
2018-12-05 20:48:13 -05:00
2018-11-29 18:26:48 -05:00
validates :resource_type,
allow_nil: true,
inclusion: { in: Rolify.resource_types }
2019-03-25 20:56:31 -04:00
###########
# Methods #
###########
2019-02-08 02:32:33 -05:00
def self.make!(role_name, resource = nil)
resource_type =
resource.is_a?(Class) ? resource.to_s : resource&.class&.name
resource_id = resource&.id unless resource.is_a? Class
find_or_create_by!(
2019-04-28 09:34:46 -04:00
name: role_name,
2019-02-08 02:32:33 -05:00
resource_type: resource_type,
2019-04-28 09:34:46 -04:00
resource_id: resource_id,
2019-02-08 02:32:33 -05:00
)
end
def human_name
I18n.translate name, scope: :roles
end
2019-02-01 21:35:58 -05:00
def human_resource
"#{resource_type} ##{resource_id}" if resource_id
end
2018-11-29 18:26:48 -05:00
end