Class: HtmlColorValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
app/validators/html_color_validator.rb

Overview

typed: ignore frozen_string_literal: true

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/validators/html_color_validator.rb', line 4

def validate(record)
  options[:keys].each do |attr|
    record.send(attr).to_s =~ /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/
    rgb = []
    rgb << Regexp.last_match(1).to_i unless Regexp.last_match(1).nil?
    rgb << Regexp.last_match(2).to_i unless Regexp.last_match(2).nil?
    rgb << Regexp.last_match(3).to_i unless Regexp.last_match(3).nil?

    record.send(attr).to_s =~ /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i
    hex = []
    hex << Regexp.last_match(1) unless Regexp.last_match(1).nil?
    hex << Regexp.last_match(2) unless Regexp.last_match(2).nil?

    unless (rgb.present? && rgb.select { |c| c >= 0 && c <= 255 }.length == 3) || (hex.present? && hex.length == 1)
      record.errors.add(attr, 'has invalid color code')
      return false
    end
  end
  true
end