Class: Decoding::Decoders::Any

Inherits:
Decoding::Decoder show all
Defined in:
lib/decoding/decoders/any.rb

Overview

A decoder wrapping any number of decoders, finding the first one that matches the given value and returning its result.

See Also:

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#failure, #to_decoder

Constructor Details

#initialize(decoder, *decoders) ⇒ Any

Returns a new instance of Any.

Parameters:



15
16
17
18
# File 'lib/decoding/decoders/any.rb', line 15

def initialize(decoder, *decoders)
  @decoders = [decoder, *decoders].map(&:to_decoder)
  super()
end

Instance Method Details

#call(value) ⇒ Decoding::Result<Object>

Parameters:

  • value (Object)

Returns:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/decoding/decoders/any.rb', line 22

def call(value)
  failures = []
  @decoders.each do |decoder|
    result = decoder.call(value)

    # NOTE: we could've pattern matched here but that would create an
    # unreachable `else` clause triggering code coverage issues. This
    # explicit way ensures we know every code path is touched.
    return result if result.ok?

    failures << result.unwrap_err(nil)
  end
  err(failure("None of the decoders matched:\n#{failures.map { "  - #{_1}" }.join("\n")}"))
end