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, "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
Атрибуты
Публичные методы класса
Передайте экземпляр объекта, использующего объект ошибок.
class Person
def initialize
@errors = ActiveModel::Errors.new(self)
end
end
# File activemodel/lib/active_model/errors.rb, line 70
def initialize(base)
@base = base
@messages = {}
end Общедоступные методы экземпляров
При передаче символа или имени метода возвращает массив ошибок для этого метода.
person.errors[:name] # => ["cannot be nil"] person.errors['name'] # => ["cannot be nil"]
# File activemodel/lib/active_model/errors.rb, line 133 def [](attribute) get(attribute.to_sym) || set(attribute.to_sym, []) end
Добавляет предоставленное сообщение об ошибке к указанному атрибуту.
person.errors[:name] = "must be set" person.errors[:name] # => ['must be set']
# File activemodel/lib/active_model/errors.rb, line 141 def []=(attribute, error) self[attribute] << error end
Добавляет message к сообщениям об ошибках для attribute. К одному и тому же attribute можно добавить несколько ошибок. Если сообщение об ошибке не указано, используется :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 # => {}
# File activemodel/lib/active_model/errors.rb, line 291
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 Добавит сообщение об ошибке к каждому атрибуту в attributes, который пустой (используя Object#blank?).
person.errors.add_on_blank(:name)
person.errors.messages
# => {:name=>["can't be blank"]}
# File activemodel/lib/active_model/errors.rb, line 321
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, который пустой.
person.errors.add_on_empty(:name)
person.errors.messages
# => {:name=>["can't be empty"]}
# File activemodel/lib/active_model/errors.rb, line 307
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 Возвращает true, если ошибка для атрибута с указанным сообщением присутствует, false, в противном случае. message обрабатывается так же, как и для add.
person.errors.add :name, :blank person.errors.added? :name, :blank # => true
# File activemodel/lib/active_model/errors.rb, line 333
def added?(attribute, message = :invalid, options = {})
message = normalize_message(attribute, message, options)
self[attribute].include? message
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 242 def as_json(options=nil) to_hash(options && options[:full_messages]) end
Очистить сообщения об ошибках.
person.errors.full_messages # => ["name cannot be nil"] person.errors.clear person.errors.full_messages # => []
# File activemodel/lib/active_model/errors.rb, line 85 def clear messages.clear end
Возвращает количество сообщений об ошибках.
person.errors.add(:name, "can't be blank") person.errors.count # => 1 person.errors.add(:name, "must be specified") person.errors.count # => 2
# File activemodel/lib/active_model/errors.rb, line 206 def count to_a.size end
Удалить сообщения для key. Возвращает удаленные сообщения.
person.errors.get(:name) # => ["cannot be nil"] person.errors.delete(:name) # => ["cannot be nil"] person.errors.get(:name) # => nil
# File activemodel/lib/active_model/errors.rb, line 124 def delete(key) messages.delete(key) 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
# File activemodel/lib/active_model/errors.rb, line 159
def each
messages.each_key do |attribute|
self[attribute].each { |error| yield attribute, error }
end
end Возвращает true, если ошибки не найдены, false, в противном случае. Если сообщение об ошибке является строкой, оно может быть пустым.
person.errors.full_messages # => ["name cannot be nil"] person.errors.empty? # => false
# File activemodel/lib/active_model/errors.rb, line 215
def empty?
all? { |k, v| v && v.empty? && !v.is_a?(String) }
end Возвращает полное сообщение для заданного атрибута.
person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
# File activemodel/lib/active_model/errors.rb, line 369
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 Возвращает все полные сообщения об ошибках в массиве.
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 348
def full_messages
map { |attribute, 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 362
def full_messages_for(attribute)
(get(attribute) || []).map { |message| full_message(attribute, message) }
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
# File activemodel/lib/active_model/errors.rb, line 404
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.class.model_name.human,
attribute: @base.class.human_attribute_name(attribute),
value: value
}.merge!(options)
I18n.translate(key, options)
end Получить сообщения для key.
person.errors.messages # => {:name=>["cannot be nil"]}
person.errors.get(:name) # => ["cannot be nil"]
person.errors.get(:age) # => nil
# File activemodel/lib/active_model/errors.rb, line 106 def get(key) messages[key] 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 95 def include?(attribute) messages[attribute].present? end
Возвращает все ключи сообщений.
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.keys # => [:name]
# File activemodel/lib/active_model/errors.rb, line 187 def keys messages.keys 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"]
# File activemodel/lib/active_model/errors.rb, line 115 def set(key, value) messages[key] = value end
Возвращает количество сообщений об ошибках.
person.errors.add(:name, "can't be blank") person.errors.size # => 1 person.errors.add(:name, "must be specified") person.errors.size # => 2
# File activemodel/lib/active_model/errors.rb, line 171 def size values.flatten.size 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"]
# File activemodel/lib/active_model/errors.rb, line 196 def to_a full_messages end
Возвращает хэш Hash атрибутов с их сообщениями об ошибках. Если 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 251
def to_hash(full_messages = false)
if full_messages
messages = {}
self.messages.each do |attribute, array|
messages[attribute] = array.map { |message| full_message(attribute, message) }
end
messages
else
self.messages.dup
end
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>
# File activemodel/lib/active_model/errors.rb, line 232
def to_xml(options={})
to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
end Возвращает все значения сообщений.
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.values # => [["cannot be nil", "must be specified"]]
# File activemodel/lib/active_model/errors.rb, line 179 def values messages.values end
© 2004–2016 David Heinemeier Hansson
Licensed under the MIT License.