Class: Decoding::Decoders::OptionalField

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

Overview

Decode a value from a key that may be absent from a hash.

This differs from wrapping a Field decoder in an Optional decoder, which describes a key that is present but may hold nil. Here the key itself may be missing; when it is present, its value must still decode.

See Also:

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#failure, #to_decoder

Constructor Details

#initialize(key, decoder, default: nil) ⇒ OptionalField

Returns a new instance of OptionalField.

Parameters:

  • key (Object)
  • decoder (Decoding::Decoder<a>)
  • default (Object) (defaults to: nil) —

    used when the key is absent.



19
20
21
22
23
24
# File 'lib/decoding/decoders/optional_field.rb', line 19

def initialize(key, decoder, default: nil)
  @key = String(key)
  @field = Field.new(@key, decoder)
  @default = default
  super()
end

Instance Method Details

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

Parameters:

  • value (Object)

Returns:



28
29
30
31
32
# File 'lib/decoding/decoders/optional_field.rb', line 28

def call(value)
  return ok(@default) if value.is_a?(::Hash) && !value.key?(@key)

  @field.call(value)
end