Class: Strict::Validators::HashOf

Inherits:
Object
  • Object
show all
Includes:
DetailedValidator
Defined in:
lib/strict/validators/hash_of.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DetailedValidator

#===

Constructor Details

#initialize(key_validator, value_validator) ⇒ HashOf



10
11
12
13
# File 'lib/strict/validators/hash_of.rb', line 10

def initialize(key_validator, value_validator)
  @key_validator = key_validator
  @value_validator = value_validator
end

Instance Attribute Details

#key_validatorObject (readonly)

Returns the value of attribute key_validator.



8
9
10
# File 'lib/strict/validators/hash_of.rb', line 8

def key_validator
  @key_validator
end

#value_validatorObject (readonly)

Returns the value of attribute value_validator.



8
9
10
# File 'lib/strict/validators/hash_of.rb', line 8

def value_validator
  @value_validator
end

Instance Method Details

#coercerObject



15
16
17
18
19
# File 'lib/strict/validators/hash_of.rb', line 15

def coercer
  key_coercer = key_validator.coercer if key_validator.respond_to?(:coercer)
  value_coercer = value_validator.coercer if value_validator.respond_to?(:coercer)
  Coercers::Hash.new(key_coercer, value_coercer)
end

#inspectObject Also known as: to_s

rubocop:enable Metrics/MethodLength



39
40
41
# File 'lib/strict/validators/hash_of.rb', line 39

def inspect
  "HashOf(#{key_validator.inspect} => #{value_validator.inspect})"
end

#violations(value) ⇒ Object

rubocop:disable Metrics/MethodLength



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/strict/validators/hash_of.rb', line 22

def violations(value)
  return Validation.invalid(self, value) unless Hash === value

  violations = nil
  value.each do |key, entry_value|
    key_violations = Validation.violations(key_validator, key)
    value_violations = Validation.violations(value_validator, entry_value)
    next if key_violations.empty? && value_violations.empty?

    violations ||= []
    violations.concat(Validation.prepend_path(key_violations, key))
    violations.concat(Validation.prepend_path(value_violations, key))
  end
  violations || Validation::NONE
end