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 AM::Errors and Dry::Validation list of error messages:

- Dry: https://github.com/dry-rb/dry-validation/blob/8417e8/config/errors.yml
- AM: https://github.com/svenfuchs/rails-i18n/blob/70b38b/rails/locale/en-US.yml#L111

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

#parseObject



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

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_aObject



55
56
57
# File 'lib/error_normalizer/message_parser.rb', line 55

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