class Validatable::Errors

Public Instance Methods

[](attribute) click to toggle source

Rails 3 API for errors, always return array.

# File lib/validatable/errors.rb, line 46
def [](attribute)
  errors[attribute.to_sym] || []
end
add_to_base(msg) click to toggle source

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.

# File lib/validatable/errors.rb, line 26
def add_to_base(msg)
  add(:base, msg)
end
full_messages → an_array_of_messages click to toggle source

Returns an array containing the full list of error messages.

# File lib/validatable/errors.rb, line 85
def full_messages
  full_messages = []

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

      if attribute.to_s == "base"
        full_messages << msg
      else
        full_messages << humanize(attribute.to_s) + " " + msg
      end
    end
  end
  full_messages
end
invalid?(attribute) click to toggle source

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

class Company < ActiveRecord::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
# File lib/validatable/errors.rb, line 18
def invalid?(attribute)
  !@errors[attribute.to_sym].nil?
end
on(attribute) click to toggle source
  • 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.

# File lib/validatable/errors.rb, line 40
def on(attribute)
  return nil if errors[attribute.to_sym].nil?
  errors[attribute.to_sym].size == 1 ? errors[attribute.to_sym].first : errors[attribute.to_sym]
end
on_base() click to toggle source

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

# File lib/validatable/errors.rb, line 31
def on_base
  on(:base)
end
raw(attribute) click to toggle source
  • Returns an array of error messages associated with the specified attribute.

# File lib/validatable/errors.rb, line 70
def raw(attribute)
  errors[attribute.to_sym]
end
replace(attribute) click to toggle source
  • Replaces the errors value for the given attribute

# File lib/validatable/errors.rb, line 63
def replace(attribute, value)
  errors[attribute.to_sym] = value
end