Class: Decoding::Decoders::Optional

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

Overview

A decoder for a value that may or may not be nil, decoding any other value with a given decoder.

The given decoder gets to decode a nil value first, so it can give it a meaning of its own. Only when it fails to do so does this decoder treat nil as an absent value.

See Also:

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#failure, #to_decoder

Constructor Details

#initialize(decoder) ⇒ Optional

Returns a new instance of Optional.

Parameters:



17
18
19
20
# File 'lib/decoding/decoders/optional.rb', line 17

def initialize(decoder)
  @decoder = decoder.to_decoder
  super()
end

Instance Method Details

#call(value) ⇒ Decoding::Result<a, nil>

Parameters:

  • value (Object)

Returns:



24
25
26
27
28
29
30
# File 'lib/decoding/decoders/optional.rb', line 24

def call(value)
  result = @decoder.call(value)
  return result if result.ok?
  return ok(nil) if value.nil?

  result
end