Class: AdequateErrors::Errors

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

Overview

Collection of Error objects. Provides convenience methods to access these errors. It is accessed via model.errors.adequate

Instance Method Summary collapse

Constructor Details

#initialize(base) ⇒ Errors


16
17
18
19
# File 'lib/adequate_errors/errors.rb', line 16

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

Instance Method Details

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

Adds error. More than one error can be added to the same `attribute`. If no `type` is supplied, `:invalid` is assumed.


38
39
40
41
42
43
44
45
46
# File 'lib/adequate_errors/errors.rb', line 38

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

  if !type.is_a? Symbol
    options[:message] = type
    type = :invalid
  end

  @errors.append(::AdequateErrors::Error.new(@base, attribute, type, options))
end

#delete(attribute) ⇒ Object

Delete errors of attribute


22
23
24
25
26
# File 'lib/adequate_errors/errors.rb', line 22

def delete(attribute)
  @errors.delete_if do |error|
    error.attribute == attribute
  end
end

#include?(attribute) ⇒ Boolean


78
79
80
# File 'lib/adequate_errors/errors.rb', line 78

def include?(attribute)
  @errors.any?{|error| error.attribute == attribute }
end

#messagesArray(String)


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

def messages
  @errors.map(&:message)
end

#messages_for(params) ⇒ Array(String)

Convenience method to fetch error messages filtered by where condition.


56
57
58
# File 'lib/adequate_errors/errors.rb', line 56

def messages_for(params)
  where(params).map(&:message)
end

#to_hashHash


83
84
85
86
87
88
89
90
91
92
93
# File 'lib/adequate_errors/errors.rb', line 83

def to_hash
  hash = {}
  @errors.each do |error|
    if hash.has_key?(error.attribute)
      hash[error.attribute] << error.message
    else
      hash[error.attribute] = [error.message]
    end
  end
  hash
end

#where(params) ⇒ Array(AdequateErrors::Error)

Returns matching AdequateErrors::Error.

Options Hash (params):

  • :attribute (Symbol)

    Filtering on attribute the error belongs to

  • :type (Symbol)

    Filter on type of error


69
70
71
72
73
74
75
# File 'lib/adequate_errors/errors.rb', line 69

def where(params)
  return @errors.dup if params.blank?

  @errors.select {|error|
    error.match?(params)
  }
end