Class: Errorio::Errors

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/errorio/errors.rb

Overview

Collection of error objects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base = nil) ⇒ Errors

Returns a new instance of Errors.



10
11
12
13
# File 'lib/errorio/errors.rb', line 10

def initialize(base = nil)
  @base = base
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly) Also known as: objects

Returns the value of attribute errors.



7
8
9
# File 'lib/errorio/errors.rb', line 7

def errors
  @errors
end

Instance Method Details

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

Adds a new error to errors collection

Parameters:

  • attribute (Symbol)
  • type (Symbol) (defaults to: :invalid)
  • options (Hash) (defaults to: {})


20
21
22
23
24
25
26
# File 'lib/errorio/errors.rb', line 20

def add(attribute, type = :invalid, options = {})
  error = Error.new(@base, attribute, type, options)

  @errors.append(error)

  error
end

#attribute_namesObject Also known as: keys

Returns all error attribute names

person.errors.messages        # => {:name=>["cannot be nil", "must be specified"]}
person.errors.attribute_names # => [:name]


49
50
51
# File 'lib/errorio/errors.rb', line 49

def attribute_names
  @errors.map(&:attribute).uniq.freeze
end

#copy(other) ⇒ Object

Copy errors from another errors object

Parameters:



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/errorio/errors.rb', line 31

def copy(other)
  other.each do |err|
    options = err.options

    # ActiveModel::Error object has own way to generate message attribute,
    # try to copy message as the property of `options`

    if (err.is_a?(ActiveModel::Error) || err.is_a?(ActiveModel::NestedError)) && options[:message].blank?
      options[:message] = err.message
    end
    add err.attribute, err.type, options
  end
end

#each(&block) ⇒ Object



64
65
66
# File 'lib/errorio/errors.rb', line 64

def each(&block)
  @errors.each(&block)
end

#full_message(attribute, message) ⇒ Object

Returns a full message for a given attribute. person.errors.full_message(:name, ‘is invalid’) # => “Name is invalid”



56
57
58
59
60
61
62
# File 'lib/errorio/errors.rb', line 56

def full_message(attribute, message)
  attr_name = attribute.to_s.tr('.', '_').humanize
  return "#{attr_name} #{message}" if @base.nil?

  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
  I18n.t(:"errors.format", default: '%{attribute} %{message}', attribute: attr_name, message: message)
end