about summary refs log tree commit diff
path: root/app/lib/validation_error_formatter.rb
blob: 1d3e8955b3ce8bb065ec99f33a480b632ef674f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# frozen_string_literal: true

class ValidationErrorFormatter
  def initialize(error, aliases = {})
    @error   = error
    @aliases = aliases
  end

  def as_json
    { error: @error.to_s, details: details }
  end

  private

  def details
    h = {}

    errors.details.each_pair do |attribute_name, attribute_errors|
      messages = errors.messages[attribute_name]

      h[@aliases[attribute_name] || attribute_name] = attribute_errors.map.with_index do |error, index|
        { error: "ERR_#{error[:error].to_s.upcase}", description: messages[index] }
      end
    end

    h
  end

  def errors
    @errors ||= @error.record.errors
  end
end