From 77873eb2917ae45b13aa88482be12a69ccbd9202 Mon Sep 17 00:00:00 2001 From: Niraj Raut <84171890+nirajkumar999@users.noreply.github.com> Date: Fri, 12 Jul 2024 00:08:47 +0530 Subject: [PATCH] Improved Role Model (#5879) * added case_sensitive: false option to name validation and updated set_role_color function to avoid collision for color property * passed rubocop test --- app/models/role.rb | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/app/models/role.rb b/app/models/role.rb index 3168c39115..c270bb1499 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -21,7 +21,8 @@ class Role < ApplicationRecord has_many :role_permissions, dependent: :destroy has_many :permissions, through: :role_permissions - validates :name, presence: true, uniqueness: { scope: :provider } + validates :name, presence: true, uniqueness: { case_sensitive: false, scope: :provider } + validates :provider, presence: true before_validation :set_role_color, on: :create @@ -59,15 +60,21 @@ def create_role_permissions private def set_role_color - self.color = case name - when 'Administrator' - '#228B22' - when 'User' - '#4169E1' - when 'Guest' - '#FFA500' - else - "##{SecureRandom.hex(3)}" - end + color = case name + when 'Administrator' + '#228B22' + when 'User' + '#4169E1' + when 'Guest' + '#FFA500' + else + "##{SecureRandom.hex(3)}" + end + + raise if Role.exists?(color:) # Ensure uniqueness + + self.color = color + rescue StandardError + retry end end