Class: Decoding::Failure

Inherits:
Object
  • Object
show all
Defined in:
lib/decoding/failure.rb

Overview

A failure is an error message, much like a string, but with an added stack of earlier messages.

This is useful to create clearer error messages when using compound decoders, such as array(string). If the string decoder fails with an error, the array decoder can push 3 to the stack to indicate that happened at index 3 in its input value.

Instance Method Summary collapse

Constructor Details

#initialize(msg, path = []) ⇒ Failure

Returns a new instance of Failure.

Parameters:

  • msg (String)
  • path (Array) (defaults to: [])

    Internal parameter for creating copies with updated paths



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

def initialize(msg, path = [])
  @msg = msg
  @path = path.dup.freeze
  freeze
end

Instance Method Details

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


20
21
22
23
24
# File 'lib/decoding/failure.rb', line 20

def eql?(other)
  other.is_a?(self.class) &&
    msg == other.msg &&
    path == other.path
end

#push(segment) ⇒ Decoding::Failure

Add segments to the stack of errors. Returns a new Failure instance with the updated path.

Parameters:

  • segment (String)

Returns:



32
33
34
# File 'lib/decoding/failure.rb', line 32

def push(segment)
  self.class.new(@msg, @path + [segment])
end

#to_sObject



36
37
38
39
40
41
42
# File 'lib/decoding/failure.rb', line 36

def to_s
  if @path.any?
    "Error at .#{@path.reverse.join(".")}: #{@msg}"
  else
    @msg
  end
end