Class: CouchFoo::Errors

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/couch_foo/validations.rb

Overview

Couch Foo validation is reported to and from this object, which is used by Base#save to determine whether the object is in a valid state to be saved. See usage example in Validations.

Constant Summary collapse

@@default_error_messages =
{
  :inclusion => "is not included in the list",
  :exclusion => "is reserved",
  :invalid => "is invalid",
  :confirmation => "doesn't match confirmation",
  :accepted  => "must be accepted",
  :empty => "can't be empty",
  :blank => "can't be blank",
  :too_long => "is too long (maximum is %d characters)",
  :too_short => "is too short (minimum is %d characters)",
  :wrong_length => "is the wrong length (should be %d characters)",
  :taken => "has already been taken",
  :not_a_number => "is not a number",
  :greater_than => "must be greater than %d",
  :greater_than_or_equal_to => "must be greater than or equal to %d",
  :equal_to => "must be equal to %d",
  :less_than => "must be less than %d",
  :less_than_or_equal_to => "must be less than or equal to %d",
  :odd => "must be odd",
  :even => "must be even"
}

Instance Method Summary collapse

Constructor Details

#initialize(base) ⇒ Errors

:nodoc:



22
23
24
# File 'lib/couch_foo/validations.rb', line 22

def initialize(base) # :nodoc:
  @base, @errors = base, {}
end

Instance Method Details

#add(attribute, msg = @@default_error_messages[:invalid]) ⇒ Object

Adds an error message (msg) to the attribute, which will be returned on a call to on(attribute) for the same attribute and ensure that this error object returns false when asked if empty?. More than one error can be added to the same attribute in which case an array will be returned on a call to on(attribute). If no msg is supplied, “invalid” is assumed.



63
64
65
66
# File 'lib/couch_foo/validations.rb', line 63

def add(attribute, msg = @@default_error_messages[:invalid])
  @errors[attribute.to_s] = [] if @errors[attribute.to_s].nil?
  @errors[attribute.to_s] << msg
end

#add_on_blank(attributes, msg = ) ⇒ Object

Will add an error message to each of the attributes in attributes that is blank (using Object#blank?).



78
79
80
81
82
83
# File 'lib/couch_foo/validations.rb', line 78

def add_on_blank(attributes, msg = @@default_error_messages[:blank])
  for attr in [attributes].flatten
    value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
    add(attr, msg) if value.blank?
  end
end

#add_on_empty(attributes, msg = ) ⇒ Object

Will add an error message to each of the attributes in attributes that is empty.



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

def add_on_empty(attributes, msg = @@default_error_messages[:empty])
  for attr in [attributes].flatten
    value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
    is_empty = value.respond_to?("empty?") ? value.empty? : false
    add(attr, msg) unless !value.nil? && !is_empty
  end
end

#add_to_base(msg) ⇒ Object

Adds an error to the base object instead of any particular attribute. This is used to report errors that don’t tie to any specific attribute, but rather to the object as a whole. These error messages don’t get prepended with any field name when iterating with each_full, so they should be complete sentences.



55
56
57
# File 'lib/couch_foo/validations.rb', line 55

def add_to_base(msg)
  add(:base, msg)
end

#clearObject

Removes all errors that have been added.



191
192
193
# File 'lib/couch_foo/validations.rb', line 191

def clear
  @errors = {}
end

#eachObject

Yields each attribute and associated message per error added.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } # =>
  name - is too short (minimum is 5 characters)
  name - can't be blank
  address - can't be blank


137
138
139
# File 'lib/couch_foo/validations.rb', line 137

def each
  @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
end

#each_fullObject

Yields each full error message added. So Person.errors.add(“first_name”, “can’t be empty”) will be returned through iteration as “First name can’t be empty”.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.each_full{|msg| puts msg } # =>
  Name is too short (minimum is 5 characters)
  Name can't be blank
  Address can't be blank


154
155
156
# File 'lib/couch_foo/validations.rb', line 154

def each_full
  full_messages.each { |msg| yield msg }
end

#empty?Boolean

Returns true if no errors have been added.

Returns:



186
187
188
# File 'lib/couch_foo/validations.rb', line 186

def empty?
  @errors.empty?
end

#full_messagesObject

Returns all the full error messages in an array.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.full_messages # =>
  ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/couch_foo/validations.rb', line 168

def full_messages
  full_messages = []

  @errors.each_key do |attr|
    @errors[attr].each do |msg|
      next if msg.nil?

      if attr == "base"
        full_messages << msg
      else
        full_messages << attr.humanize + " " + msg
      end
    end
  end
  full_messages
end

#invalid?(attribute) ⇒ Boolean

Returns true if the specified attribute has errors associated with it.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.invalid?(:name)      # => true
company.errors.invalid?(:address)   # => false

Returns:



95
96
97
# File 'lib/couch_foo/validations.rb', line 95

def invalid?(attribute)
  !@errors[attribute.to_s].nil?
end

#on(attribute) ⇒ Object Also known as: []

Returns nil, if no errors are associated with the specified attribute. Returns the error message, if one error is associated with the specified attribute. Returns an array of error messages, if more than one error is associated with the specified attribute.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
company.errors.on(:email)     # => "can't be blank"
company.errors.on(:address)   # => nil


112
113
114
115
116
# File 'lib/couch_foo/validations.rb', line 112

def on(attribute)
  errors = @errors[attribute.to_s]
  return nil if errors.nil?
  errors.size == 1 ? errors.first : errors
end

#on_baseObject

Returns errors assigned to the base object through add_to_base according to the normal rules of on(attribute).



121
122
123
# File 'lib/couch_foo/validations.rb', line 121

def on_base
  on(:base)
end

#sizeObject Also known as: count, length

Returns the total number of errors added. Two errors added to the same attribute will be counted as such.



196
197
198
# File 'lib/couch_foo/validations.rb', line 196

def size
  @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
end

#to_xml(options = {}) ⇒ Object

Returns an XML representation of this error object.

class Company < CouchFoo::Base
  validates_presence_of :name, :address, :email
  validates_length_of :name, :in => 5..30
end

company = Company.create(:address => '123 First St.')
company.errors.to_xml # =>
  <?xml version="1.0" encoding="UTF-8"?>
  <errors>
    <error>Name is too short (minimum is 5 characters)</error>
    <error>Name can't be blank</error>
    <error>Address can't be blank</error>
  </errors>


218
219
220
221
222
223
224
225
226
227
# File 'lib/couch_foo/validations.rb', line 218

def to_xml(options={})
  options[:root] ||= "errors"
  options[:indent] ||= 2
  options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])

  options[:builder].instruct! unless options.delete(:skip_instruct)
  options[:builder].errors do |e|
    full_messages.each { |msg| e.error(msg) }
  end
end