DRY up Color model validations

This commit is contained in:
Alexander Brandon Coles
2025-08-14 23:50:25 +01:00
parent 79ab560806
commit 2ec7690a02
3 changed files with 7 additions and 5 deletions
+2 -3
View File
@@ -38,9 +38,8 @@ class Color < ApplicationRecord
dependent: :nullify
validates :name, :hexcode, presence: true
validates :name, length: { maximum: 255, unless: lambda { |e| e.name.blank? } }
validates :hexcode, format: { with: /\A#[0-9A-F]{6}\z/, unless: lambda { |e| e.hexcode.blank? } }
validates :name, length: { maximum: 255 }
validates :hexcode, format: { with: RGB_HEX_FORMAT, allow_blank: true }
normalizes :hexcode, with: ::Colors::HexColor::Normalizer
end
+3
View File
@@ -30,6 +30,9 @@
module Colors
module HexColor
RGB_HEX_FORMAT = /\A#[0-9A-F]{6}\z/
private_constant :RGB_HEX_FORMAT
##
# Get the fill style for this color.
# If the color is light, use a dark font.
+2 -2
View File
@@ -43,9 +43,9 @@ class DesignColor < ApplicationRecord
end
end
validates :variable, :hexcode, presence: true
validates :variable, uniqueness: true
validates :hexcode, :variable, presence: true
validates :hexcode, format: { with: /\A#[0-9A-F]{6}\z/, unless: lambda { |e| e.hexcode.blank? } }
validates :hexcode, format: { with: RGB_HEX_FORMAT, allow_blank: true }
normalizes :hexcode, with: ::Colors::HexColor::Normalizer