Thursday, September 19, 2024 11:58:11 PM
> settings

Customize


Authenticate

> role.rb
# frozen_string_literal: true

class Role < ApplicationRecord
  include PublicIdConcern

  ALL = [
    DEVMAN = {
      id: 0, name: "devman", permissions: Permission::ALL.keys
    },
    TRUSTED = {
      id: 1,
      name: "trusted",
      permissions: %i[
        user_self_modify
        trusted_view
        professional_view
        file_view
        post_view
        project_view
      ]
    },
    PROFESSIONAL = {
      id: 2,
      name: "professional",
      permissions: %i[
        user_self_modify
        professional_view
        post_view
        project_view
      ]
    },
    UNTRUSTED = {
      id: 3,
      name: "untrusted",
      permissions: %i[
        post_view
        project_view
      ]
    }
  ].freeze

  ###########################################
  # Attributes
  attribute :public_id, :public_id
  attribute :name, :string
  attribute :value, :integer
  attribute :permissions, :permissions_as_array

  ###########################################
  # Associations
  has_many :users, dependent: :restrict_with_exception

  ###########################################
  # Scopes
  scope :devman, -> { where(name: "devman").first }
  scope :trusted, -> { where(name: "trusted").first }
  scope :professional, -> { where(name: "professional").first }
  scope :untrusted, -> { where(name: "untrusted").first }

  ###########################################

  def self.calculated_value
    all.pluck(:value).reduce(:|)
  end

  def self.calculate(*role_names)
    ids = role_names.map { |name| ALL.find { |r| r[:name].to_s == name.to_s }[:id] }

    query = reselect("bit_or(value)").where(id: ids).to_sql
    connection.exec_query(query).cast_values.first
  end

  def permission?(name)
    permissions.include?(name.to_sym.downcase)
  end
end
All opinions represented herein are my own
- © 2024 itsthedevman
- build 3c15a1b