Class: FulfilApi::Resource::Errors

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/fulfil_api/resource/errors.rb

Overview

The Errors class provides a structure to track and manage errors related to a API resource.

Instance Method Summary collapse

Constructor Details

#initialize(resource_klass) ⇒ Errors

Returns a new instance of Errors.

Parameters:

  • resource_klass (FulfilApi::Resource)

    The resource class that this Errors instance is associated with.



12
13
14
15
# File 'lib/fulfil_api/resource/errors.rb', line 12

def initialize(resource_klass)
  @errors = []
  @resource_klass = resource_klass
end

Instance Method Details

#add(code:, message:, type:) ⇒ Array<Hash>

Adds a new error to the collection, unless the same error already exists.

Examples:

Adding an error

errors.add(code: "invalid_field", message: "Field is required", type: "validation")

Parameters:

  • code (String, Symbol)

    The error code.

  • message (String)

    A description of the error.

  • type (String, Symbol)

    The type of the error (e.g. user, authorization).

Returns:

  • (Array<Hash>)

    The updated list of errors.



26
27
28
29
# File 'lib/fulfil_api/resource/errors.rb', line 26

def add(code:, message:, type:)
  @errors << { code: code.to_s, type: type.to_sym, message: message } unless added?(code: code, type: type)
  @errors
end

#added?(code:, type:) ⇒ Boolean

Checks if an error with the specified code and type has already been added.

Examples:

Checking if an error exists

errors.added?(code: "invalid_field", type: "validation")

Parameters:

  • code (String, Symbol)

    The error code to check.

  • type (String, Symbol)

    The error type to check.

Returns:

  • (Boolean)

    True if the error has already been added, false otherwise.



39
40
41
42
43
# File 'lib/fulfil_api/resource/errors.rb', line 39

def added?(code:, type:)
  @errors.any? do |error|
    error[:code] == code.to_s && error[:type] == type.to_sym
  end
end

#clearArray

Clears all errors from the collection.

Examples:

Clearing all errors

errors.clear

Returns:

  • (Array)

    The cleared list of errors



51
52
53
54
# File 'lib/fulfil_api/resource/errors.rb', line 51

def clear
  @errors = []
  @errors
end

#full_messagesArray<String>

Returns an array of the full error messages (just the message field).

Examples:

Retrieving full error messages

errors.full_messages

Returns:

  • (Array<String>)

    The list of error messages.



62
63
64
# File 'lib/fulfil_api/resource/errors.rb', line 62

def full_messages
  @errors.pluck(:message)
end

#messagesArray<Hash>

Returns the collection of error messages as an array of hashes.

Examples:

Retrieving all error messages

errors.messages

Returns:

  • (Array<Hash>)

    The array of error hashes.



72
73
74
# File 'lib/fulfil_api/resource/errors.rb', line 72

def messages
  @errors
end