class StValidation::Validators::HashValidator

Attributes

validators[R]

Public Class Methods

new(blueprint, factory) click to toggle source
# File lib/st_validation/validators/hash_validator.rb, line 6
def initialize(blueprint, factory)
  @validators = blueprint.map { |k, bp| [k, factory.build(bp)] }.to_h
end

Public Instance Methods

call(value) click to toggle source
# File lib/st_validation/validators/hash_validator.rb, line 10
def call(value)
  return false unless value.is_a?(Hash) && extra_keys(value).empty?

  validators.each { |k, v| return false unless v.call(value[k]) }
  true
end

Private Instance Methods

extra_keys(hash) click to toggle source
# File lib/st_validation/validators/hash_validator.rb, line 33
def extra_keys(hash)
  hash.keys - validators.keys
end
generate_explanation(value) click to toggle source
# File lib/st_validation/validators/hash_validator.rb, line 21
def generate_explanation(value)
  return 'not a hash' unless value.is_a?(Hash)

  result = validators
           .reduce({}) { |a, (k, v)| a.merge(k => v.explain(value[k])) }
           .compact

  extra_keys(value).each { |k| result[k] = 'extra key detected' }

  result.empty? ? nil : result
end