Module: Brainstem::Concerns::ErrorPresentation

Extended by:
ActiveSupport::Concern
Included in:
Brainstem::ControllerMethods
Defined in:
lib/brainstem/concerns/error_presentation.rb

Instance Method Summary collapse

Instance Method Details

#brainstem_full_error_message(object, attribute, text) ⇒ Object

Helper to convert an attribute name (e.g., “thing_id”) and error (e.g., “is invalid”) into a combined full message. Also handles traditional “^You messed up”-style errors that should not be combined with humanized attribute names.



53
54
55
# File 'lib/brainstem/concerns/error_presentation.rb', line 53

def brainstem_full_error_message(object, attribute, text)
  text[0] == "^" ? text[1..-1] : object.errors.full_message(attribute, text)
end

#brainstem_model_error(object_or_objects, options = {}) ⇒ Object

Given a model or models, outputs Brainstem-style errors, for example:

{ :errors => [{ :type => 'validation', :field => :thing_id, :message => "Thing is required" }] }

If given a rewrite_params hash, it will convert from an internal column name to an external name. Note: you must validate models prior to passing them into this method. It does not call `valid?` on them.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/brainstem/concerns/error_presentation.rb', line 23

def brainstem_model_error(object_or_objects, options = {})
  json = { :errors => [] }

  [object_or_objects].flatten.each.with_index do |object, index|
    case object
      when Hash
        attribute = object[:field] || :base
        json[:errors] << {
          :type => object[:type] || 'validation',
          :field => (options[:rewrite_params] || {}).reverse_merge(attribute => attribute).invert[attribute],
          :message => object[:message] || raise(ArgumentError, "message required")
        }
      when String
        json[:errors] << { :type => 'validation', :field => :base, :message => object }
      else
        object.errors.each do |attribute, attribute_error|
          json[:errors] << {
            :type => 'validation',
            :field => (options[:rewrite_params] || {}).reverse_merge(attribute => attribute).invert[attribute],
            :message => brainstem_full_error_message(object, attribute, attribute_error),
            :index => index
          }
        end
    end
  end
  json
end

#brainstem_system_error(*messages) ⇒ Object

Given one or more error messages, return Brainstem-style errors, defaulting to type 'system'.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/brainstem/concerns/error_presentation.rb', line 7

def brainstem_system_error(*messages)
  options = messages.last.is_a?(Hash) ? messages.pop : {}
  response = { :errors => [] }
  messages.flatten.uniq.each do |message|
    response[:errors] << {
      :type => options[:type] || :system,
      :message => message
    }
  end
  response
end