Class: Sequel::Model::Errors

Inherits:
Hash show all
Defined in:
lib/sequel/model/errors.rb

Overview

Errors represents validation errors, a simple hash subclass with a few convenience methods.

Constant Summary collapse

ATTRIBUTE_JOINER =
' and '.freeze

Instance Method Summary collapse

Methods inherited from Hash

#&, #case, #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
# File 'lib/sequel/model/errors.rb', line 12

def [](k)
  has_key?(k) ? super : (self[k] = [])
end

#add(att, msg) ⇒ Object

Adds an error for the given attribute.

errors.add(:name, 'is not valid') if name == 'invalid'


19
20
21
# File 'lib/sequel/model/errors.rb', line 19

def add(att, msg)
  self[att] << msg
end

#countObject

Return the total number of error messages.

errors.count # => 3


26
27
28
# File 'lib/sequel/model/errors.rb', line 26

def count
  values.inject(0){|m, v| m + v.length}
end

#empty?Boolean

Return true if there are no error messages, false otherwise.

Returns:

  • (Boolean)


31
32
33
# File 'lib/sequel/model/errors.rb', line 31

def empty?
  count == 0
end

#full_messagesObject

Returns an array of fully-formatted error messages.

errors.full_messages
# => ['name is not valid',
#     'hometown is not at least 2 letters']


40
41
42
43
44
45
46
# File 'lib/sequel/model/errors.rb', line 40

def full_messages
  inject([]) do |m, kv| 
    att, errors = *kv
    errors.each {|e| m << "#{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


53
54
55
56
57
# File 'lib/sequel/model/errors.rb', line 53

def on(att)
  if v = fetch(att, nil) and !v.empty?
    v
  end
end