Class: Code42Api::Errors

Inherits:
ActiveModel::Errors
  • Object
show all
Defined in:
lib/code42_api/errors.rb

Constant Summary collapse

STANDARD_ERROR =
"StandardError"
ERROR_MAPPINGS =
{
  'PresenceError' => [
    :blank,
    :empty,
    :present
  ],
  'LengthError' => [
    :too_long,
    :too_short,
    :wrong_length
  ],
  'BoundError' => [
    :greater_than,
    :greater_than_or_equal_to,
    :equal_to,
    :less_than,
    :less_than_or_equal_to,
    :other_than,
    :odd,
    :even
  ],
  'TypeError' => [
    :not_a_number,
    :not_an_integer
  ],
  'AcceptanceError' => [:accepted],
  'FormatError' => [:invalid],
  'InclusionError' => [
    :inclusion,
    :exclusion
  ]
}

Instance Method Summary collapse

Instance Method Details

#add(attribute, message = :invalid, options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/code42_api/errors.rb', line 41

def add(attribute, message = :invalid, options = {})
  type = get_type(message, options)

  message = normalize_message(attribute, message, options)
  if exception = options[:strict]
    exception = ActiveModel::StrictValidationFailed if exception == true
    raise exception, full_message(attribute, message)
  end

  self[attribute] << ErrorMessage.new(message, type)
end

#as_json(options = nil) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/code42_api/errors.rb', line 67

def as_json(options = nil)
  errors = []
  to_hash.each do |(attribute_name,values)|
    values.each do |value|
      errors << {
        name: attribute_name,
        type: value.type,
        description: value,
      }
    end
  end
  errors.as_json(options)
end

#get_type(message, options) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/code42_api/errors.rb', line 53

def get_type(message, options)
  if options[:error_type]
    options[:error_type]
  elsif message.is_a?(Symbol)
    type_from_symbol(message)
  else
    STANDARD_ERROR
  end
end

#type_from_symbol(symbol) ⇒ Object



63
64
65
# File 'lib/code42_api/errors.rb', line 63

def type_from_symbol(symbol)
  ERROR_MAPPINGS.keys.detect { |k| ERROR_MAPPINGS[k].include?(symbol) } || STANDARD_ERROR
end