Class: ActiveModel::Validations::RangeValidator

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

Constant Summary collapse

OPTIONS =
[:overlapping, :not_overlapping].freeze

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



14
15
16
17
18
19
# File 'lib/range_validator.rb', line 14

def check_validity!
  options.each do |option, option_value|
    next if option_value.is_a?(Symbol) || option_value.is_a?(Proc)
    raise ArgumentError, ":#{option} must be a symbol or a proc"
  end
end

#validate_each(record, attribute, value) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/range_validator.rb', line 21

def validate_each(record, attribute, value)
  unless value.is_a? Range
    record.errors.add(attribute, :not_a_range)
    return
  end

  options.slice(*OPTIONS).each do |option, option_value|
    other_records = retrieve_other_records(record, option_value)

    if option == :overlapping && other_records.blank?
      record.errors.add(attribute, :no_overlap)
    end

    other_records.each do |other_record|
      overlap = value.overlaps? other_record.send(attribute)

      if option == :overlapping && !overlap
        record.errors.add(attribute, :no_overlap)
      elsif option == :not_overlapping && overlap
        record.errors.add(attribute, :overlap)
      end
    end
  end
end