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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# File 'lib/hash_validator/validators/array_validator.rb', line 14
def validate(key, value, specification, errors)
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
return if specification.size < 2
array_spec = specification[1]
return if array_spec.nil?
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]
size_spec_present = case size_spec
when String
!object.strip.empty?
when NilClass
false
when Numeric
true
when Array, Hash
!object.empty?
else
!!object
end
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
|