Class: Sequel::Model::Errors
Overview
Errors represents validation errors, a simple hash subclass with a few convenience methods.
Direct Known Subclasses
Constant Summary collapse
- ATTRIBUTE_JOINER =
' and '.freeze
Instance Method Summary collapse
-
#[](k) ⇒ Object
Assign an array of messages for each attribute on access.
-
#add(att, msg) ⇒ Object
Adds an error for the given attribute.
-
#count ⇒ Object
Return the total number of error messages.
-
#empty? ⇒ Boolean
Return true if there are no error messages, false otherwise.
-
#full_messages ⇒ Object
Returns an array of fully-formatted error messages.
-
#on(att) ⇒ Object
Returns the array of errors for the given attribute, or nil if there are no errors for the attribute.
Methods inherited from Hash
#&, #case, #hstore, #pg_json, #sql_expr, #sql_negate, #sql_or, #|, #~
Instance Method Details
#[](k) ⇒ Object
Assign an array of messages for each attribute on access. Using this message is discouraged in new code, use add
to add new error messages, and on
to check existing error messages.
12 13 14 15 16 17 18 19 |
# File 'lib/sequel/model/errors.rb', line 12 def [](k) if has_key?(k) super else Sequel::Deprecation.deprecate('Model::Errors#[] autovivification', 'Please switch to Model::Errors#add to add errors, and Model::Errors#on to get errors') self[k] = [] end end |
#add(att, msg) ⇒ Object
Adds an error for the given attribute.
errors.add(:name, 'is not valid') if name == 'invalid'
24 25 26 |
# File 'lib/sequel/model/errors.rb', line 24 def add(att, msg) fetch(att){self[att] = []} << msg end |
#count ⇒ Object
Return the total number of error messages.
errors.count # => 3
31 32 33 |
# File 'lib/sequel/model/errors.rb', line 31 def count values.inject(0){|m, v| m + v.length} end |
#empty? ⇒ Boolean
Return true if there are no error messages, false otherwise.
36 37 38 |
# File 'lib/sequel/model/errors.rb', line 36 def empty? count == 0 end |
#full_messages ⇒ Object
Returns an array of fully-formatted error messages.
errors.
# => ['name is not valid',
# 'hometown is not at least 2 letters']
45 46 47 48 49 50 51 |
# File 'lib/sequel/model/errors.rb', line 45 def inject([]) do |m, kv| att, errors = *kv errors.each {|e| m << (e.is_a?(LiteralString) ? e : "#{Array(att).join(ATTRIBUTE_JOINER)} #{e}")} m end end |
#on(att) ⇒ Object
Returns the array of errors for the given attribute, or nil if there are no errors for the attribute.
errors.on(:name) # => ['name is not valid']
errors.on(:id) # => nil
58 59 60 61 62 |
# File 'lib/sequel/model/errors.rb', line 58 def on(att) if v = fetch(att, nil) and !v.empty? v end end |