class ActiveModel::Errors
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
Атрибуты
Публичные методы класса
# File activemodel/lib/active_model/errors.rb, line 74
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
Общедоступные методы экземпляра
# File activemodel/lib/active_model/errors.rb, line 149 def [](attribute) messages[attribute.to_sym] end
При передаче символа или имени метода возвращает массив ошибок для этого метода.
person.errors[:name] # => ["cannot be nil"] person.errors['name'] # => ["cannot be nil"]
# File activemodel/lib/active_model/errors.rb, line 295
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}]}
# File activemodel/lib/active_model/errors.rb, line 324
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
# File activemodel/lib/active_model/errors.rb, line 235 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"]}
# File activemodel/lib/active_model/errors.rb, line 115 def clear messages.clear details.clear end
Очистить сообщения об ошибках.
person.errors.full_messages # => ["name cannot be nil"] person.errors.clear person.errors.full_messages # => []
# File activemodel/lib/active_model/errors.rb, line 138 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] # => []
# File activemodel/lib/active_model/errors.rb, line 167
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
# File activemodel/lib/active_model/errors.rb, line 209 def empty? size.zero? end
Возвращает true, если ошибки не найдены, false, в противном случае. Если сообщение об ошибке является строкой, оно может быть пустым.
person.errors.full_messages # => ["name cannot be nil"] person.errors.empty? # => false
# File activemodel/lib/active_model/errors.rb, line 367
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"
# File activemodel/lib/active_model/errors.rb, line 344
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"]
# File activemodel/lib/active_model/errors.rb, line 359
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"]
# File activemodel/lib/active_model/errors.rb, line 401
def generate_message(attribute, type = :invalid, options = {})
type = options.delete(:message) if options[:message].is_a?(Symbol)
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}"
else
defaults = []
end
defaults << :"errors.attributes.#{attribute}.#{type}"
defaults << :"errors.messages.#{type}"
key = defaults.shift
defaults = options.delete(:message) if options[:message]
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,
object: @base
}.merge!(options)
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
# File activemodel/lib/active_model/errors.rb, line 126 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
# File activemodel/lib/active_model/errors.rb, line 198
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]
# File activemodel/lib/active_model/errors.rb, line 105
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)
# File activemodel/lib/active_model/errors.rb, line 179 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
# File activemodel/lib/active_model/errors.rb, line 244
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"]}
# File activemodel/lib/active_model/errors.rb, line 225
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>
# File activemodel/lib/active_model/errors.rb, line 188
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–2018 David Heinemeier Hansson
Licensed under the MIT License.