Class: EasyTalk::ErrorFormatter::Base Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_talk/error_formatter/base.rb

Overview

This class is abstract.

Subclass and implement #format to create a formatter.

Abstract base class for error formatters.

Provides common functionality for transforming ActiveModel::Errors into standardized formats. Subclasses implement the format method to produce specific output formats.

Examples:

Creating a custom formatter

class CustomFormatter < EasyTalk::ErrorFormatter::Base
  def format
    error_entries.map do |entry|
      { custom_field: entry[:attribute], custom_message: entry[:message] }
    end
  end
end

Direct Known Subclasses

Flat, JsonPointer, Jsonapi, Rfc7807

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(errors, options = {}) ⇒ Base

Initialize a new formatter.

Parameters:

  • errors (ActiveModel::Errors)

    The errors object to format

  • options (Hash) (defaults to: {})

    Formatting options

Options Hash (options):

  • :include_codes (Boolean)

    Whether to include error codes



30
31
32
33
# File 'lib/easy_talk/error_formatter/base.rb', line 30

def initialize(errors, options = {})
  @errors = errors
  @options = options
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



23
24
25
# File 'lib/easy_talk/error_formatter/base.rb', line 23

def errors
  @errors
end

#optionsObject (readonly)

Returns the value of attribute options.



23
24
25
# File 'lib/easy_talk/error_formatter/base.rb', line 23

def options
  @options
end

Instance Method Details

#error_entriesArray<Hash> (protected)

Build a normalized list of error entries from ActiveModel::Errors.

Each entry contains:

  • :attribute - The attribute name (may include dots for nested)
  • :message - The error message
  • :full_message - The full error message with attribute name
  • :type - The error type from errors.details (e.g., :blank, :too_short)
  • :detail_options - Additional options from the error detail

Returns:

  • (Array<Hash>)

    The normalized error entries



63
64
65
# File 'lib/easy_talk/error_formatter/base.rb', line 63

def error_entries
  @error_entries ||= build_error_entries
end

#formatHash, Array

This method is abstract.

Format the errors into the target format.

Returns:

  • (Hash, Array)

    The formatted errors

Raises:

  • (NotImplementedError)

    if the subclass does not implement this method



40
41
42
# File 'lib/easy_talk/error_formatter/base.rb', line 40

def format
  raise NotImplementedError, "#{self.class} must implement #format"
end

#include_codes?Boolean (protected)

Check if error codes should be included in the output.

Returns:

  • (Boolean)


49
50
51
# File 'lib/easy_talk/error_formatter/base.rb', line 49

def include_codes?
  @options.fetch(:include_codes, EasyTalk.configuration.include_error_codes)
end