Class: ErrorNormalizer::MessageParser

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

Overview

Parse error messages and extract payload metadata.

ActiveModel ignored for now because we don’t plan to use its validations. In case message isn’t recognized we set error to be a simple normalized message (no spaces and special characters).

Here are the links to ActiveModel::Errors and Dry::Validation list of error messages:

Constant Summary collapse

VALUE_MATCHERS =
[
  /\A(?<err>must not include) (?<val>.+)/,
  /\A(?<err>must be equal to) (?<val>.+)/,
  /\A(?<err>must not be equal to) (?<val>.+)/,
  /\A(?<err>must be greater than) (?<val>\d+)/,
  /\A(?<err>must be greater than or equal to) (?<val>\d+)/,
  /\A(?<err>must include) (?<val>.+)/,
  /\A(?<err>must be less than) (?<val>\d+)/,
  /\A(?<err>must be less than or equal to) (?<val>\d+)/,
  /\A(?<err>size cannot be greater than) (?<val>\d+)/,
  /\A(?<err>size cannot be less than) (?<val>\d+)/,
  /\A(?<err>size must be) (?<val>\d+)/,
  /\A(?<err>length must be) (?<val>\d+)/
].freeze
LIST_MATCHERS =
[
  /\A(?<err>must not be one of): (?<val>.+)/,
  /\A(?<err>must be one of): (?<val>.+)/,
  /\A(?<err>size must be within) (?<val>.+)/,
  /\A(?<err>length must be within) (?<val>.+)/
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(message) ⇒ MessageParser

Returns a new instance of MessageParser.



38
39
40
41
42
# File 'lib/error_normalizer/message_parser.rb', line 38

def initialize(message)
  @message = message
  @key = nil
  @payload = {}
end

Instance Method Details

#parseArray

Parse error message

Returns:

  • (Array)

    a tuple of parsed [key, message, payload]



46
47
48
49
50
51
52
53
54
55
# File 'lib/error_normalizer/message_parser.rb', line 46

def parse
  parse_value_message
  return to_a if @key

  parse_list_message
  return to_a if @key

  @key = to_key(@message)
  to_a
end

#to_aArray

Returns a tuple of parsed [key, message, payload].

Returns:

  • (Array)

    a tuple of parsed [key, message, payload]



58
59
60
# File 'lib/error_normalizer/message_parser.rb', line 58

def to_a
  [@key, @message, @payload]
end