Spec-Zone.ru › Ruby on Rails 4.2

class ActiveModel::Errors

Parent:
Object
Included modules:
Enumerable

Объекты ошибок Active Model

Предоставляет модифицированный Hash для включения в ваш объект для обработки сообщений об ошибках и взаимодействия с помощниками Action View.

Минимальная реализация может быть такой:

class Person
  # Required dependency for ActiveModel::Errors
  extend ActiveModel::Naming

  def initialize
    @errors = ActiveModel::Errors.new(self)
  end

  attr_accessor :name
  attr_reader   :errors

  def validate!
    errors.add(:name, "cannot be nil") if name.nil?
  end

  # The following methods are needed to be minimally implemented

  def read_attribute_for_validation(attr)
    send(attr)
  end

  def Person.human_attribute_name(attr, options = {})
    attr
  end

  def Person.lookup_ancestors
    [self]
  end
end

Последние три метода необходимы в вашем объекте, чтобы Errors могли правильно генерировать сообщения об ошибках, а также обрабатывать несколько языков. Конечно, если вы расширяете свой объект с помощью ActiveModel::Translation, вам не нужно реализовывать последние два. Аналогично, использование ActiveModel::Validations позволит обрабатывать методы, связанные с валидацией.

Вышеприведённое позволяет вам сделать следующее:

person = Person.new
person.validate!            # => ["cannot be nil"]
person.errors.full_messages # => ["name cannot be nil"]
# etc..

Константы

CALLBACKS_OPTIONS

Атрибуты

messages[R]

Открытые методы класса

new(base) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 70
def initialize(base)
  @base     = base
  @messages = {}
end

Передайте экземпляр объекта, использующего объект ошибок.

class Person
  def initialize
    @errors = ActiveModel::Errors.new(self)
  end
end

Общедоступные методы экземпляра

[](attribute) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 135
def [](attribute)
  get(attribute.to_sym) || set(attribute.to_sym, [])
end

При передаче символа или имени метода возвращает массив ошибок для этого метода.

person.errors[:name]  # => ["cannot be nil"]
person.errors['name'] # => ["cannot be nil"]
[]=(attribute, error) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 143
def []=(attribute, error)
  self[attribute] << error
end

Добавляет предоставленное сообщение об ошибке к указанному атрибуту.

person.errors[:name] = "must be set"
person.errors[:name] # => ['must be set']
add(attribute, message = :invalid, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 298
def add(attribute, message = :invalid, options = {})
  message = normalize_message(attribute, message, options)
  if exception = options[:strict]
    exception = ActiveModel::StrictValidationFailed if exception == true
    raise exception, full_message(attribute, message)
  end

  self[attribute] << message
end

Добавляет message к сообщениям об ошибках для attribute. Можно добавить несколько ошибок к одному и тому же attribute. Если message не указано, предполагается :invalid.

person.errors.add(:name)
# => ["is invalid"]
person.errors.add(:name, 'must be implemented')
# => ["is invalid", "must be implemented"]

person.errors.messages
# => {:name=>["must be implemented", "is invalid"]}

Если message является символом, он будет переведен с использованием соответствующего контекста (см. generate_message).

Если message является процедурой, она будет вызвана, что позволит использовать, например, Time.now в ошибке.

Если опция :strict установлена в true, она будет вызывать ActiveModel::StrictValidationFailed вместо добавления ошибки. Опция :strict также может быть установлена на любой другой тип исключения.

person.errors.add(:name, nil, strict: true)
# => ActiveModel::StrictValidationFailed: name is invalid
person.errors.add(:name, nil, strict: NameIsInvalid)
# => NameIsInvalid: name is invalid

person.errors.messages # => {}

attribute должно быть установлено в :base, если ошибка не напрямую связана с одним атрибутом.

person.errors.add(:base, "either name or email must be present")
person.errors.messages
# => {:base=>["either name or email must be present"]}
add_on_blank(attributes, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 328
def add_on_blank(attributes, options = {})
  Array(attributes).each do |attribute|
    value = @base.send(:read_attribute_for_validation, attribute)
    add(attribute, :blank, options) if value.blank?
  end
end

Добавит сообщение об ошибке к каждому из атрибутов в attributes, которые пусты (используя Object#blank?).

person.errors.add_on_blank(:name)
person.errors.messages
# => {:name=>["can't be blank"]}
add_on_empty(attributes, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 314
def add_on_empty(attributes, options = {})
  Array(attributes).each do |attribute|
    value = @base.send(:read_attribute_for_validation, attribute)
    is_empty = value.respond_to?(:empty?) ? value.empty? : false
    add(attribute, :empty, options) if value.nil? || is_empty
  end
end

Добавит сообщение об ошибке к каждому из атрибутов в attributes, которые пусты.

person.errors.add_on_empty(:name)
person.errors.messages
# => {:name=>["can't be empty"]}
added?(attribute, message = :invalid, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 340
def added?(attribute, message = :invalid, options = {})
  message = normalize_message(attribute, message, options)
  self[attribute].include? message
end

Возвращает true, если присутствует ошибка для атрибута с данным сообщением, false в противном случае. message обрабатывается так же, как и для add.

person.errors.add :name, :blank
person.errors.added? :name, :blank # => true
as_json(options=nil) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 244
def as_json(options=nil)
  to_hash(options && options[:full_messages])
end

Возвращает Hash, который можно использовать в качестве JSON-представления этого объекта. Вы можете передать опцию :full_messages. Это определяет, должен ли json-объект содержать полные сообщения или нет (по умолчанию false).

person.errors.as_json                      # => {:name=>["cannot be nil"]}
person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]}
blank?()

является псевдонимом для empty?

Псевдоним для: empty?
clear() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 85
def clear
  messages.clear
end

Очистить сообщения об ошибках.

person.errors.full_messages # => ["name cannot be nil"]
person.errors.clear
person.errors.full_messages # => []
count() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 208
def count
  to_a.size
end

Возвращает количество сообщений об ошибках.

person.errors.add(:name, "can't be blank")
person.errors.count # => 1
person.errors.add(:name, "must be specified")
person.errors.count # => 2
delete(key) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 126
def delete(key)
  messages.delete(key)
end

Удалить сообщения для key. Возвращает удаленные сообщения.

person.errors.get(:name)    # => ["cannot be nil"]
person.errors.delete(:name) # => ["cannot be nil"]
person.errors.get(:name)    # => nil
each() { |attribute, error| ... } Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 161
def each
  messages.each_key do |attribute|
    self[attribute].each { |error| yield attribute, error }
  end
end

Перебирает каждую пару ключ-значение в хэше сообщений об ошибках. Вызывает метод для атрибута и ошибки для этого атрибута. Если у атрибута более одного сообщения об ошибке, вызов производится для каждого сообщения об ошибке.

person.errors.add(:name, "can't be blank")
person.errors.each do |attribute, error|
  # Will yield :name and "can't be blank"
end

person.errors.add(:name, "must be specified")
person.errors.each do |attribute, error|
  # Will yield :name and "can't be blank"
  # then yield :name and "must be specified"
end
empty?() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 217
def empty?
  all? { |k, v| v && v.empty? && !v.is_a?(String) }
end

Возвращает true, если ошибок не найдено, false в противном случае. Если сообщение об ошибке — строка, оно может быть пустым.

person.errors.full_messages # => ["name cannot be nil"]
person.errors.empty?        # => false
Также является псевдонимом для: blank?
full_message(attribute, message) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 376
def full_message(attribute, message)
  return message if attribute == :base
  attr_name = attribute.to_s.tr('.', '_').humanize
  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
  I18n.t(:"errors.format", {
    default:  "%{attribute} %{message}",
    attribute: attr_name,
    message:   message
  })
end

Возвращает полное сообщение для заданного атрибута.

person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
full_messages() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 355
def full_messages
  map { |attribute, message| full_message(attribute, message) }
end

Возвращает все полные сообщения об ошибках в массиве.

class Person
  validates_presence_of :name, :address, :email
  validates_length_of :name, in: 5..30
end

person = Person.create(address: '123 First St.')
person.errors.full_messages
# => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
full_messages_for(attribute) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 369
def full_messages_for(attribute)
  (get(attribute) || []).map { |message| full_message(attribute, message) }
end

Возвращает все полные сообщения об ошибках для заданного атрибута в массиве.

class Person
  validates_presence_of :name, :email
  validates_length_of :name, in: 5..30
end

person = Person.create()
person.errors.full_messages_for(:name)
# => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
generate_message(attribute, type = :invalid, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 411
def generate_message(attribute, type = :invalid, options = {})
  type = options.delete(:message) if options[:message].is_a?(Symbol)

  if @base.class.respond_to?(:i18n_scope)
    defaults = @base.class.lookup_ancestors.map do |klass|
      [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
        :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
    end
  else
    defaults = []
  end

  defaults << options.delete(:message)
  defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
  defaults << :"errors.attributes.#{attribute}.#{type}"
  defaults << :"errors.messages.#{type}"

  defaults.compact!
  defaults.flatten!

  key = defaults.shift
  value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)

  options = {
    default: defaults,
    model: @base.model_name.human,
    attribute: @base.class.human_attribute_name(attribute),
    value: value
  }.merge!(options)

  I18n.translate(key, options)
end

Переводит сообщение об ошибке в его стандартном контексте (activemodel.errors.messages).

Сообщения об ошибках сначала ищутся в models.MODEL.attributes.ATTRIBUTE.MESSAGE, если их нет, то в models.MODEL.MESSAGE, а если и там нет, возвращается перевод стандартного сообщения (например, activemodel.errors.messages.MESSAGE). Переведенное имя модели, переведенное имя атрибута и значение доступны для интерполяции.

При использовании наследования в ваших моделях он также проверяет все унаследованные модели, но только если модель сама не найдена. Допустим, у вас есть class Admin < User; end и вы хотели перевод ошибки :blank для атрибута title, он ищет эти переводы:

  • activemodel.errors.models.admin.attributes.title.blank

  • activemodel.errors.models.admin.blank

  • activemodel.errors.models.user.attributes.title.blank

  • activemodel.errors.models.user.blank

  • любой стандарт, который вы предоставили через хэш options (в контексте activemodel.errors)

  • activemodel.errors.messages.blank

  • errors.attributes.title.blank

  • errors.messages.blank

get(key) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 108
def get(key)
  messages[key]
end

Получить сообщения для key.

person.errors.messages   # => {:name=>["cannot be nil"]}
person.errors.get(:name) # => ["cannot be nil"]
person.errors.get(:age)  # => nil
has_key?(attribute)

является псевдонимом для include?

Псевдоним для: include?
include?(attribute) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 95
def include?(attribute)
  messages[attribute].present?
end

Возвращает true если сообщения об ошибках содержат ошибку для заданного ключа attribute, false в противном случае.

person.errors.messages        # => {:name=>["cannot be nil"]}
person.errors.include?(:name) # => true
person.errors.include?(:age)  # => false
Также использует алиасы: has_key?, key?
key?(attribute)

алиас include?

Псевдоним для: include?
keys() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 189
def keys
  messages.keys
end

Возвращает все ключи сообщений.

person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.keys     # => [:name]
set(key, value) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 117
def set(key, value)
  messages[key] = value
end

Устанавливает сообщения для key в value.

person.errors.get(:name) # => ["cannot be nil"]
person.errors.set(:name, ["can't be nil"])
person.errors.get(:name) # => ["can't be nil"]
size() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 173
def size
  values.flatten.size
end

Возвращает количество сообщений об ошибках.

person.errors.add(:name, "can't be blank")
person.errors.size # => 1
person.errors.add(:name, "must be specified")
person.errors.size # => 2
to_a() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 198
def to_a
  full_messages
end

Возвращает массив сообщений об ошибках, включая имя атрибута.

person.errors.add(:name, "can't be blank")
person.errors.add(:name, "must be specified")
person.errors.to_a # => ["name can't be blank", "name must be specified"]
to_hash(full_messages = false) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 253
def to_hash(full_messages = false)
  if full_messages
    self.messages.each_with_object({}) do |(attribute, array), messages|
      messages[attribute] = array.map { |message| full_message(attribute, message) }
    end
  else
    self.messages.dup
  end
end

Возвращает словарь атрибутов с их сообщениями об ошибках. Если full_messages равно true, он будет содержать полные сообщения (см. full_message).

person.errors.to_hash       # => {:name=>["cannot be nil"]}
person.errors.to_hash(true) # => {:name=>["name cannot be nil"]}
to_xml(options={}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 234
def to_xml(options={})
  to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
end

Возвращает xml-форматированное представление словаря Errors.

person.errors.add(:name, "can't be blank")
person.errors.add(:name, "must be specified")
person.errors.to_xml
# =>
#  <?xml version=\"1.0\" encoding=\"UTF-8\"?>
#  <errors>
#    <error>name can't be blank</error>
#    <error>name must be specified</error>
#  </errors>
values() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 181
def values
  messages.values
end

Возвращает все значения сообщений.

person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.values   # => [["cannot be nil", "must be specified"]]

© 2004–2018 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API