Class: Decoding::Decoders::Index

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

Overview

Decode the element at a specific offset in an array.

See Also:

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#failure, #to_decoder

Constructor Details

#initialize(index, decoder) ⇒ Index

Returns a new instance of Index.

Parameters:



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

def initialize(index, decoder)
  @index = index.to_int
  @decoder = decoder.to_decoder
  super()
end

Instance Method Details

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

Parameters:

  • value (Object)

Returns:



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

def call(value)
  return err(failure("expected Array, got #{value.class}")) unless value.is_a?(::Array)

  @decoder
    .call(value.fetch(@index))
    .map_err { _1.push(@index) }
rescue IndexError => e
  err(failure("error decoding array: #{e}"))
end