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:

Constant Summary collapse

Err =
Result.err("error decoding array: index is out of bounds")

Instance Method Summary collapse

Methods inherited from Decoding::Decoder

#to_decoder

Constructor Details

#initialize(index, decoder) ⇒ Index

Returns a new instance of Index.

Parameters:



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

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:



25
26
27
28
29
30
31
32
33
# File 'lib/decoding/decoders/index.rb', line 25

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

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