Class: Errorio::Errors
- Inherits:
-
Object
- Object
- Errorio::Errors
- Extended by:
- Forwardable
- Defined in:
- lib/errorio/errors.rb
Overview
Collection of error objects
Instance Attribute Summary collapse
-
#errors ⇒ Object
(also: #objects)
readonly
Returns the value of attribute errors.
Instance Method Summary collapse
-
#add(attribute, type = :invalid, options = {}) ⇒ Object
Adds a new error to errors collection.
-
#attribute_names ⇒ Object
(also: #keys)
Returns all error attribute names.
-
#copy(other) ⇒ Object
Copy errors from another errors object.
- #each(&block) ⇒ Object
-
#full_message(attribute, message) ⇒ Object
Returns a full message for a given attribute.
-
#initialize(base = nil) ⇒ Errors
constructor
A new instance of Errors.
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
#errors ⇒ Object (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
20 21 22 23 24 25 26 |
# File 'lib/errorio/errors.rb', line 20 def add(attribute, type = :invalid, = {}) error = Error.new(@base, attribute, type, ) @errors.append(error) error end |
#attribute_names ⇒ Object Also known as: keys
Returns all error attribute names
person.errors. # => {: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
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| = err. # 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)) && [:message].blank? [:message] = err. end add err.attribute, err.type, 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 (attribute, ) attr_name = attribute.to_s.tr('.', '_').humanize return "#{attr_name} #{}" 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: ) end |