Class: EasyJSONMatcher::ValidatorSet

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_json_matcher/validator_set.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(validators:, strict: false) ⇒ ValidatorSet

Returns a new instance of ValidatorSet.



8
9
10
11
# File 'lib/easy_json_matcher/validator_set.rb', line 8

def initialize(validators:, strict: false)
  @validators = validators
  @strict = strict
end

Instance Attribute Details

#strictObject

Returns the value of attribute strict.



6
7
8
# File 'lib/easy_json_matcher/validator_set.rb', line 6

def strict
  @strict
end

#validatorsObject

Returns the value of attribute validators.



6
7
8
# File 'lib/easy_json_matcher/validator_set.rb', line 6

def validators
  @validators
end

Instance Method Details

#call(value:) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/easy_json_matcher/validator_set.rb', line 13

def call(value:)
  error_hash = validators.each_with_object({}) do |k_v, errors_found|
    key = k_v[0]
    val = value[key.to_s]
    validator = k_v[1]
    results = validator.call(value: val)
    errors_found[key] = results unless results.empty?
  end
  validate_strict_keyset(keys: validators.keys, candidates: value.keys, errors: error_hash) if strict
  if error_hash.empty? then [] else [error_hash] end
end

#missing_keys(keys:, errors:, candidates:) ⇒ Object



30
31
32
33
# File 'lib/easy_json_matcher/validator_set.rb', line 30

def missing_keys(keys:, errors:, candidates:)
  missing = keys - candidates
  errors[:missing_keys] = "Missing keys: #{missing}" unless missing.empty?
end

#unexpected_keys(keys:, errors:, candidates:) ⇒ Object



35
36
37
38
# File 'lib/easy_json_matcher/validator_set.rb', line 35

def unexpected_keys(keys:, errors:, candidates:)
  rogue_keys = candidates - keys
  errors[:unexpected_keys] = "Unexpected keys: #{rogue_keys}" unless rogue_keys.empty?
end

#validate_strict_keyset(keys:, errors:, candidates:) ⇒ Object



25
26
27
28
# File 'lib/easy_json_matcher/validator_set.rb', line 25

def validate_strict_keyset(keys:, errors:, candidates:)
  missing_keys(keys: keys, errors: errors, candidates: candidates)
  unexpected_keys(keys: keys, errors: errors, candidates: candidates)
end