Class: HashValidator::Validator::ArrayValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/hash_validator/validators/array_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#name

Instance Method Summary collapse

Methods inherited from Base

#presence_error_message

Constructor Details

#initializeArrayValidator

Returns a new instance of ArrayValidator.



2
3
4
# File 'lib/hash_validator/validators/array_validator.rb', line 2

def initialize
  super('__array__')  # The name of the validator, underscored as it won't usually be directly invoked (invoked through use of validator)
end

Instance Method Details

#should_validate?(rhs) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
9
10
11
12
# File 'lib/hash_validator/validators/array_validator.rb', line 6

def should_validate?(rhs)
  return false unless rhs.is_a?(Array)
  return false unless rhs.size > 0
  return false unless rhs[0] == :array

  return true
end

#validate(key, value, specification, errors) ⇒ Object



14
15
16
17
18
19
20
21
22
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
60
61
62
63
# File 'lib/hash_validator/validators/array_validator.rb', line 14

def validate(key, value, specification, errors)
  # the first item in specification is always ":array"
  unless specification[0] == :array
    errors[key] = "Wrong array specification. The #{:array} is expected as first item."
    return
  end

  if specification.size > 2
    errors[key] = "Wrong size of array specification. Allowed is one or two items."
    return
  end

  unless value.is_a?(Array)
    errors[key] = "#{Array} required"
    return
  end

  # second item is optional
  return if specification.size < 2

  array_spec = specification[1]
  return if array_spec.nil? # array specification is optional

  if array_spec.is_a?(Numeric)
    array_spec = { size: array_spec }
  end

  unless array_spec.is_a?(Hash)
    errors[key] = "Second item of array specification must be #{Hash} or #{Numeric}."
    return
  end

  return if array_spec.empty?

  size_spec = array_spec[:size]
  if size_spec.present?
    unless value.size == size_spec
      errors[key] = "The required size of array is #{size_spec} but is #{value.size}."
      return
    end
  end

  allowed_keys = [:size]
  wrong_keys = array_spec.keys - allowed_keys

  return if wrong_keys.size < 1

  errors[key] = "Not supported specification for array: #{wrong_keys.sort.join(", ")}."
  return
end