Class: ApiClient::Errors

Inherits:
ActiveModel::Errors
  • Object
show all
Defined in:
lib/api-client/errors.rb

Overview

ApiClient::Errors provide extra functionality to ActiveModel::Errors.

Instance Method Summary collapse

Instance Method Details

#add_errors(errors = {}) ⇒ ApiClient::Errors

Add several errors from a hash to the object.

Parameters:

  • errors (Hash) (defaults to: {})

    The hash with errors to add.

Returns:


9
10
11
12
13
# File 'lib/api-client/errors.rb', line 9

def add_errors(errors = {})
  errors.each_pair do |key, value|
    add(key, value)
  end
end

#unique_message(attribute) ⇒ String

Returns a unique message for a given attribute.

class Person
  validates_presence_of :name, :address, :email
  validates_length_of :name, in: 5..30
end

person = Person.create(address: '123 First St.')
person.errors.unique_message(:name) # => "is too short (minimum is 5 characters) and can't be blank"
person.errors.unique_message(:address) # => nil

Parameters:

  • attribute (String)

    The attribute to check for joined error messages.

Returns:

  • (String)

    A string with all errors from the given attribute joined.


44
45
46
47
# File 'lib/api-client/errors.rb', line 44

def unique_message(attribute)
  return '' if messages[attribute].blank?
  [messages[attribute]].flatten.to_sentence
end

#unique_messagesHash

Returns a unique message for each array of error messages in a hash.

class Person
  validates_presence_of :name, :address, :email
  validates_length_of :name, in: 5..30
end

person = Person.create(address: '123 First St.')
person.errors.unique_messages
# => { :name => "is too short (minimum is 5 characters) and can't be blank", :address => nil, :email => "can't be blank" }

Returns:

  • (Hash)

    A hash with all the errors joined by attribute.


26
27
28
29
30
# File 'lib/api-client/errors.rb', line 26

def unique_messages
  errors = {}
  map { |attribute, messages| errors[attribute] = unique_message(attribute) }
  errors
end