Class: AWS::Record::LengthValidator

Inherits:
Validator
  • Object
show all
Defined in:
lib/aws/record/validators/length.rb

Constant Summary collapse

ACCEPTED_OPTIONS =
[
  :exactly, :within, :minimum, :maximum,
  :too_long, :too_short, :wrong_length,
  :allow_nil, :on, :if, :unless,
]

Instance Attribute Summary

Attributes inherited from Validator

#attribute_names, #options

Instance Method Summary collapse

Methods inherited from Validator

#initialize, #validate

Constructor Details

This class inherits a constructor from AWS::Record::Validator

Instance Method Details

#setup(record_class) ⇒ Object


28
29
30
31
32
33
34
# File 'lib/aws/record/validators/length.rb', line 28

def setup record_class
  ensure_at_least_one(:within, :exactly, :minimum, :maximum)
  ensure_exclusive(:within, :exactly, [:minimum, :maximum])
  ensure_type(Range, :within)
  ensure_type(Integer, :exactly, :minimum, :maximum)
  ensure_type(String, :too_long, :too_short, :wrong_length)
end

#validate_attribute(record, attribute_name, value_or_values) ⇒ Object


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/aws/record/validators/length.rb', line 36

def validate_attribute record, attribute_name, value_or_values
  each_value(value_or_values) do |value|

    length = value.respond_to?(:length) ? value.length : value.to_s.length

    if exact = options[:exactly]
      unless length == exact
        record.errors.add(attribute_name, wrong_length(exact, length))
      end
    end

    if within = options[:within]
      if length < within.first
        record.errors.add(attribute_name, too_short(within.first, length))
      end
      if length > within.last
        record.errors.add(attribute_name, too_long(within.last, length))
      end
    end

    if min = options[:minimum]
      if length < min
        record.errors.add(attribute_name, too_short(min, length))
      end
    end

    if max = options[:maximum]
      if length > max
        record.errors.add(attribute_name, too_long(max, length))
      end
    end

  end
end