Class: AdequateErrors::Errors
- Inherits:
-
Object
- Object
- AdequateErrors::Errors
- 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
-
#add(attribute, type = :invalid, options = {}) ⇒ Object
Adds error.
-
#delete(attribute) ⇒ Object
Delete errors of attribute.
-
#include?(attribute) ⇒ Boolean
Whether the given attribute contains error.
-
#initialize(base) ⇒ Errors
constructor
A new instance of Errors.
-
#messages ⇒ Array(String)
All error messages.
-
#messages_for(params) ⇒ Array(String)
Convenience method to fetch error messages filtered by where condition.
-
#to_hash ⇒ Hash
Attributes with their error messages.
-
#where(params) ⇒ Array(AdequateErrors::Error)
Matching Error.
Constructor Details
#initialize(base) ⇒ Errors
Returns a new instance of 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, = {}) if !type.is_a? Symbol [:message] = type type = :invalid end @errors.append(::AdequateErrors::Error.new(@base, attribute, type, )) 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
Returns whether the given attribute contains error.
78 79 80 |
# File 'lib/adequate_errors/errors.rb', line 78 def include?(attribute) @errors.any?{|error| error.attribute == attribute } end |
#messages ⇒ Array(String)
Returns all error messages.
49 50 51 |
# File 'lib/adequate_errors/errors.rb', line 49 def @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 (params) where(params).map(&:message) end |
#to_hash ⇒ Hash
Returns attributes with their error messages.
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. else hash[error.attribute] = [error.] end end hash end |
#where(params) ⇒ Array(AdequateErrors::Error)
Returns matching AdequateErrors::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 |