Skip to content

Commit

Permalink
Improved Role Model (#5879)
Browse files Browse the repository at this point in the history
* added case_sensitive: false option to name validation and updated set_role_color function to avoid collision for color property

* passed rubocop test
  • Loading branch information
nirajkumar999 authored Jul 11, 2024
1 parent 6939e1e commit 77873eb
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions app/models/role.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

0 comments on commit 77873eb

Please sign in to comment.