Class: ErrorNormalizer::Normalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/error_normalizer/normalizer.rb

Overview

Convert given input to the array of normalized errors.

Examples:

errors = { phone: ['not plausible'] }
ErrorNormalizer::Normalizer.new(errors, namespace: 'customer').normalize
# [{
#   key: 'not_plausible',
#   message: 'not plausible',
#   payload: { path: 'customer.phone' },
#   type: 'params'
# }]

Constant Summary collapse

UnsupportedInputTypeError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, namespace: nil, **config) ⇒ Normalizer

Returns a new instance of Normalizer.



26
27
28
29
30
31
# File 'lib/error_normalizer/normalizer.rb', line 26

def initialize(input, namespace: nil, **config)
  @input = input
  @namespace = namespace
  @errors = []
  @config = config
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



24
25
26
# File 'lib/error_normalizer/normalizer.rb', line 24

def errors
  @errors
end

Instance Method Details

#add_error(error, path: nil, **options) ⇒ Error, Hash

Add new error object to the collection of processed errors. This is a more low-level method which is used by #normalize.

Returns:



36
37
38
39
40
41
42
43
44
# File 'lib/error_normalizer/normalizer.rb', line 36

def add_error(error, path: nil, **options)
  @errors <<
    case error
    when Error
      error
    when Symbol, String
      parse_error(error, path, options)
    end
end

#normalizeself

Primary method to normalize the given input

Returns:

  • (self)


48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/error_normalizer/normalizer.rb', line 48

def normalize
  if Error === @input
    add_error(@input.dup)
  elsif @input.is_a?(Hash)
    normalize_hash(@input.dup)
  elsif @input.respond_to?(:to_hash)
    normalize_hash(@input.to_hash)
  else
    raise UnsupportedInputTypeError
  end

  self
end

#to_aArray<Hash>

Returns normalized errors of Error#to_hash.

Returns:



63
64
65
# File 'lib/error_normalizer/normalizer.rb', line 63

def to_a
  @errors.map(&:to_hash)
end