From 2ec7690a02cbdbe5aa311bcc99e903eb3c4e1acb Mon Sep 17 00:00:00 2001 From: Alexander Brandon Coles Date: Thu, 14 Aug 2025 23:50:25 +0100 Subject: [PATCH] DRY up Color model validations --- app/models/color.rb | 5 ++--- app/models/colors/hex_color.rb | 3 +++ app/models/design_color.rb | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/app/models/color.rb b/app/models/color.rb index ff4dd8ae343..1fefd536f7b 100644 --- a/app/models/color.rb +++ b/app/models/color.rb @@ -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 diff --git a/app/models/colors/hex_color.rb b/app/models/colors/hex_color.rb index f06dd82f179..4a37b639601 100644 --- a/app/models/colors/hex_color.rb +++ b/app/models/colors/hex_color.rb @@ -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. diff --git a/app/models/design_color.rb b/app/models/design_color.rb index aa1ca32d377..10cff1b7619 100644 --- a/app/models/design_color.rb +++ b/app/models/design_color.rb @@ -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