Class: ActiveModel::Validations::DimensionValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/dimension_validation/dimension_validator.rb

Constant Summary collapse

DIMENSIONS =
[:width, :height, :aspect_ratio].freeze
CHECKS =
{ greater_than: :>, greater_than_or_equal_to: :>=,
equal_to: :==, less_than: :<, less_than_or_equal_to: :<= }.freeze

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/dimension_validation/dimension_validator.rb', line 9

def check_validity!
  options.slice(*DIMENSIONS).each do |dimension, dimension_options|
    if dimension_options.empty?
      raise ArgumentError, "You must at least pass in one of these options for #{dimension} - #{CHECKS.keys.join(', ')}"
    end

    dimension_options.slice(*CHECKS.keys).each do |option, value|
      unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
        raise ArgumentError, ":#{option} of #{dimension} must be a number, a symbol or a proc"
      end
    end
  end
end

#validate_each(record, attr_name, value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dimension_validation/dimension_validator.rb', line 23

def validate_each(record, attr_name, value)
  unless with_width_and_height?(value)
    record.errors.add(attr_name, 'dimension.without_width_or_height'.to_sym, filtered_options(value))
    return
  end

  result = {}
  [:width, :height].each do |dimension|
    length = value.send(dimension)
    unless is_number?(length)
      dimension_text = I18n.t(dimension, scope: 'errors.messages.dimension')
      record.errors.add(attr_name, 'dimension.not_a_number'.to_sym, filtered_options(value).merge!(dimension: dimension_text))
      return
    end

    result[dimension] = length
  end
  result[:aspect_ratio] = (result[:width] / result[:height].to_f)

  options.slice(*DIMENSIONS).each do |dimension, dimension_options|
    computed_value = result[dimension]
    dimension_text = I18n.t(dimension, scope: 'errors.messages.dimension')

    dimension_options.slice(*CHECKS.keys).each do |option, option_value|
      case option_value
      when Proc
        option_value = option_value.call(record)
      when Symbol
        option_value = record.send(option_value)
      end

      unless computed_value.send(CHECKS[option], option_value)
        record.errors.add(attr_name, "dimension.#{option}".to_sym, filtered_options(value).merge!(dimension: dimension_text, count: option_value))
      end
    end
  end
end