Class: DataValidator::LengthValidator

Inherits:
BaseValidator show all
Defined in:
lib/validations/length.rb

Constant Summary collapse

MESSAGES =
{ :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
CHECKS =
{ :is => :==, :minimum => :>=, :maximum => :<= }.freeze

Instance Attribute Summary

Attributes inherited from BaseValidator

#errors, #name, #options, #value

Instance Method Summary collapse

Methods inherited from BaseValidator

#error_add, #initialize

Constructor Details

This class inherits a constructor from DataValidator::BaseValidator

Instance Method Details

#check_validity!Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/validations/length.rb', line 8

def check_validity!
  if range = (options.delete(:in) || options.delete(:within))
    raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
    options[:minimum], options[:maximum] = range.begin, range.end
    options[:maximum] -= 1 if range.exclude_end?
  end

  keys = CHECKS.keys & options.keys
  if keys.empty?
    raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
  end

  keys.each do |key|
    option_value = options[key]
    unless option_value.is_a?(Integer) && option_value >= 0
      raise ArgumentError, ":#{key} must be a nonnegative Integer"
    end
  end
end

#validateObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/validations/length.rb', line 28

def validate
  tokenized_value = tokenize value
  value_length = tokenized_value.respond_to?(:length) ? tokenized_value.length : tokenized_value.to_s.length

  CHECKS.each do |key, validity_check|
    next unless check_value = options[key]
    next if value_length.send(validity_check, check_value)
    error_add MESSAGES[key], count: check_value
  end
end