Class: Decoding::Decoders::Field

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

Overview

Decode a value from key in a given hash.

See Also:

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#failure, #to_decoder

Constructor Details

#initialize(key, decoder) ⇒ Field

Returns a new instance of Field.

Parameters:



13
14
15
16
17
# File 'lib/decoding/decoders/field.rb', line 13

def initialize(key, decoder)
  @key = key.to_str
  @decoder = decoder.to_decoder
  super()
end

Instance Method Details

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

Parameters:

  • value (Object)

Returns:

  • (Deceoding::Result<a>)


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/decoding/decoders/field.rb', line 21

def call(value)
  if value.is_a?(::Hash)
    if value.key?(@key)
      @decoder.call(value.fetch(@key)).map_err { _1.push(@key) }
    else
      err(failure("expected a Hash with key #{@key}"))
    end
  else
    err(failure("expected a Hash, got: #{value.inspect}"))
  end
end