Class: MediaTypes::Scheme::RulesExhaustedGuard

Inherits:
Object
  • Object
show all
Defined in:
lib/media_types/scheme/rules_exhausted_guard.rb

Constant Summary collapse

EMPTY_MARK =
->(_) {}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output, options, rules:) ⇒ RulesExhaustedGuard

Returns a new instance of RulesExhaustedGuard.



18
19
20
21
22
# File 'lib/media_types/scheme/rules_exhausted_guard.rb', line 18

def initialize(output, options, rules:)
  self.rules = rules
  self.output = output
  self.options = options
end

Class Method Details

.call(*args, **opts, &block) ⇒ Object



13
14
15
# File 'lib/media_types/scheme/rules_exhausted_guard.rb', line 13

def call(*args, **opts, &block)
  new(*args, **opts).call(&block)
end

Instance Method Details

#callObject



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/media_types/scheme/rules_exhausted_guard.rb', line 24

def call
  unless options.exhaustive
    return iterate(EMPTY_MARK)
  end

  required_rules = rules.required(loose: options.loose)
  # noinspection RubyScope
  result = iterate(->(key) { required_rules.remove(key) })
  return result if required_rules.empty?

  raise_exhausted!(missing_keys: required_rules.keys, backtrace: options.backtrace, found: output)
end

#iterate(mark) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/media_types/scheme/rules_exhausted_guard.rb', line 37

def iterate(mark)
  OutputIteratorWithPredicate.call(output, options, rules: rules) do |key, value, options:, context:|
    unless key.class == options.expected_key_type || rules.get(key).class == NotStrict
      raise ValidationError,
          format(
            'Expected key as %<type>s, got %<actual>s at [%<backtrace>s]',
            type: options.expected_key_type,
            actual: key.class,
            backtrace: options.trace(key).backtrace.join('->')
          )
    end

    mark.call(key)

    catch(:end) do
      rules.get(key).validate!(
        value,
        options.trace(key),
        context: context
      )
    end
  end
end