Exception: Grape::Exceptions::ValidationErrors

Inherits:
Base
  • Object
show all
Includes:
Enumerable
Defined in:
lib/grape/exceptions/validation_errors.rb

Constant Summary collapse

ERRORS_FORMAT_KEY =
'grape.errors.format'
DEFAULT_ERRORS_FORMAT =
'%{attributes} %{message}'

Constants inherited from Base

Base::BASE_ATTRIBUTES_KEY, Base::BASE_MESSAGES_KEY, Base::FALLBACK_LOCALE

Instance Attribute Summary collapse

Attributes inherited from Base

#headers, #message, #status

Instance Method Summary collapse

Methods inherited from Base

#[]

Constructor Details

#initialize(errors: [], headers: {}, **_options) ⇒ ValidationErrors

Returns a new instance of ValidationErrors.


15
16
17
18
19
20
21
22
23
# File 'lib/grape/exceptions/validation_errors.rb', line 15

def initialize(errors: [], headers: {}, **_options)
  @errors = {}
  errors.each do |validation_error|
    @errors[validation_error.params] ||= []
    @errors[validation_error.params] << validation_error
  end

  super message: full_messages.join(', '), status: 400, headers: headers
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors


13
14
15
# File 'lib/grape/exceptions/validation_errors.rb', line 13

def errors
  @errors
end

Instance Method Details

#as_json(**_opts) ⇒ Object


33
34
35
36
37
38
39
40
# File 'lib/grape/exceptions/validation_errors.rb', line 33

def as_json(**_opts)
  errors.map do |k, v|
    {
      params: k,
      messages: v.map(&:to_s)
    }
  end
end

#eachObject


25
26
27
28
29
30
31
# File 'lib/grape/exceptions/validation_errors.rb', line 25

def each
  errors.each_pair do |attribute, errors|
    errors.each do |error|
      yield attribute, error
    end
  end
end

#full_messagesObject


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/grape/exceptions/validation_errors.rb', line 46

def full_messages
  messages = map do |attributes, error|
    I18n.t(
      ERRORS_FORMAT_KEY,
      default: DEFAULT_ERRORS_FORMAT,
      attributes: translate_attributes(attributes),
      message: error.message
    )
  end
  messages.uniq!
  messages
end

#to_json(**_opts) ⇒ Object


42
43
44
# File 'lib/grape/exceptions/validation_errors.rb', line 42

def to_json(**_opts)
  as_json.to_json
end