Spec-Zone.ru › Ruby on Rails 6.0

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, :blank, message: "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 self.human_attribute_name(attr, options = {})
    attr
  end

  def self.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
MESSAGE_OPTIONS

Атрибуты

details[R]
messages[R]

Публичные методы класса

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

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

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

Методы экземпляра публичного интерфейса

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

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

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

  details[attribute.to_sym]  << detail
  messages[attribute.to_sym] << message
end

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

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

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

person.errors.details
# => {:name=>[{error: :not_implemented}, {error: :invalid}]}

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

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

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

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

person.errors.messages # => {}

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

person.errors.add(:base, :name_or_email_blank,
  message: "either name or email must be present")
person.errors.messages
# => {:base=>["either name or email must be present"]}
person.errors.details
# => {:base=>[{error: :name_or_email_blank}]}
added?(attribute, message = :invalid, options = {}) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 340
def added?(attribute, message = :invalid, options = {})
  message = message.call if message.respond_to?(:call)

  if message.is_a? Symbol
    details[attribute.to_sym].include? normalize_detail(message, options)
  else
    self[attribute].include? message
  end
end

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

person.errors.add :name, :blank
person.errors.added? :name, :blank           # => true
person.errors.added? :name, "can't be blank" # => true

Если сообщение об ошибке требует опций, возвращает true с правильными опциями или false с неправильными или отсутствующими опциями.

person.errors.add :name, :too_long, { count: 25 }
person.errors.added? :name, :too_long, count: 25                     # => true
person.errors.added? :name, "is too long (maximum is 25 characters)" # => true
person.errors.added? :name, :too_long, count: 24                     # => false
person.errors.added? :name, :too_long                                # => false
person.errors.added? :name, "is too long"                            # => false
as_json(options = nil) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 251
def as_json(options = nil)
  to_hash(options && options[:full_messages])
end

Возвращает словарь, который может быть использован в качестве 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?
clear() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 131
def clear
  messages.clear
  details.clear
end

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

person.errors.full_messages # => ["name cannot be nil"]
person.errors.clear
person.errors.full_messages # => []
count()
Псевдоним для: size
delete(key) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 154
def delete(key)
  attribute = key.to_sym
  details.delete(attribute)
  messages.delete(attribute)
end

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

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

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

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

person.errors.add(:name, :not_specified, message: "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 225
def empty?
  size.zero?
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 412
def full_message(attribute, message)
  return message if attribute == :base
  attribute = attribute.to_s

  if self.class.i18n_customize_full_message && @base.class.respond_to?(:i18n_scope)
    attribute = attribute.remove(/\[\d\]/)
    parts = attribute.split(".")
    attribute_name = parts.pop
    namespace = parts.join("/") unless parts.empty?
    attributes_scope = "#{@base.class.i18n_scope}.errors.models"

    if namespace
      defaults = @base.class.lookup_ancestors.map do |klass|
        [
          :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.attributes.#{attribute_name}.format",
          :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.format",
        ]
      end
    else
      defaults = @base.class.lookup_ancestors.map do |klass|
        [
          :"#{attributes_scope}.#{klass.model_name.i18n_key}.attributes.#{attribute_name}.format",
          :"#{attributes_scope}.#{klass.model_name.i18n_key}.format",
        ]
      end
    end

    defaults.flatten!
  else
    defaults = []
  end

  defaults << :"errors.format"
  defaults << "%{attribute} %{message}"

  attr_name = attribute.tr(".", "_").humanize
  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)

  I18n.t(defaults.shift,
    default:  defaults,
    attribute: attr_name,
    message:   message)
end

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

person.errors.full_message(:name, 'is invalid') # => "Name is invalid"

Формат ошибки «%{attribute} %{message}» можно переопределить либо

  • activemodel.errors.models.person/contacts/addresses.attributes.street.format

  • activemodel.errors.models.person/contacts/addresses.format

  • activemodel.errors.models.person.attributes.name.format

  • activemodel.errors.models.person.format

  • errors.format

full_messages() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 381
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"]
Также является псевдонимом для: to_a
full_messages_for(attribute) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 396
def full_messages_for(attribute)
  attribute = attribute.to_sym
  messages[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 480
def generate_message(attribute, type = :invalid, options = {})
  type = options.delete(:message) if options[:message].is_a?(Symbol)
  value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)

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

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

    catch(:exception) do
      translation = I18n.translate(defaults.first, options.merge(default: defaults.drop(1), throw: true))
      return translation unless translation.nil?
    end unless options[:message]
  else
    defaults = []
  end

  defaults << :"errors.attributes.#{attribute}.#{type}"
  defaults << :"errors.messages.#{type}"

  key = defaults.shift
  defaults = options.delete(:message) if options[:message]
  options[:default] = defaults

  I18n.translate(key, options)
end

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

Сообщение об ошибке сначала ищется в activemodel.errors.models.MODEL.attributes.ATTRIBUTE.MESSAGE, если его там нет, то ищется в activemodel.errors.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

has_key?(attribute)
Псевдоним для: include?
include?(attribute) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 142
def include?(attribute)
  attribute = attribute.to_sym
  messages.key?(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?
keys() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 214
def keys
  messages.select do |key, value|
    !value.empty?
  end.keys
end

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

person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.keys     # => [:name]
merge!(other) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 110
def merge!(other)
  @messages.merge!(other.messages) { |_, ary1, ary2| ary1 + ary2 }
  @details.merge!(other.details) { |_, ary1, ary2| ary1 + ary2 }
end

Объединяет ошибки из other.

other - Экземпляр ActiveModel::Errors.

Примеры

person.errors.merge!(other)
END_OF_DOCUMENT_MARKER
of_kind?(attribute, message = :invalid) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 361
def of_kind?(attribute, message = :invalid)
  message = message.call if message.respond_to?(:call)

  if message.is_a? Symbol
    details[attribute.to_sym].map { |e| e[:error] }.include? message
  else
    self[attribute].include? message
  end
end

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

person.errors.add :age
person.errors.add :name, :too_long, { count: 25 }
person.errors.of_kind? :age                                            # => true
person.errors.of_kind? :name                                           # => false
person.errors.of_kind? :name, :too_long                                # => true
person.errors.of_kind? :name, "is too long (maximum is 25 characters)" # => true
person.errors.of_kind? :name, :not_too_long                            # => false
person.errors.of_kind? :name, "is too long"                            # => false
size() Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 195
def size
  values.flatten.size
end

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

person.errors.add(:name, :blank, message: "can't be blank")
person.errors.size # => 1
person.errors.add(:name, :not_specified, message: "must be specified")
person.errors.size # => 2
Также алиасировано как: count
slice!(*keys) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 120
def slice!(*keys)
  keys = keys.map(&:to_sym)
  @details.slice!(*keys)
  @messages.slice!(*keys)
end

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

person.errors.keys                  # => [:name, :age, :gender, :city]
person.errors.slice!(:age, :gender) # => { :name=>["cannot be nil"], :city=>["cannot be nil"] }
person.errors.keys                  # => [:age, :gender]
to_a()
Псевдоним для: full_messages
to_hash(full_messages = false) Показать исходный код
# File activemodel/lib/active_model/errors.rb, line 260
def to_hash(full_messages = false)
  if full_messages
    messages.each_with_object({}) do |(attribute, array), messages|
      messages[attribute] = array.map { |message| full_message(attribute, message) }
    end
  else
    without_default_proc(messages)
  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 241
def to_xml(options = {})
  to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
end

Возвращает xml-представление хэша Errors.

person.errors.add(:name, :blank, message: "can't be blank")
person.errors.add(:name, :not_specified, message: "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 204
def values
  messages.select do |key, value|
    !value.empty?
  end.values
end

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

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

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

Spec-Zone.ru

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