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 72
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 172 def [](attribute) messages[attribute.to_sym] end
При передаче символа или имени метода возвращает массив ошибок для метода.
person.errors[:name] # => ["cannot be nil"] person.errors['name'] # => ["cannot be nil"]
Обратите внимание, что если вы попытаетесь получить ошибки атрибута, у которого нет связанных с ним ошибок, этот метод создаст для него пустой список ошибок и keys вернет массив ключей ошибок, который включает этот атрибут.
person.errors.keys # => [] person.errors[:name] # => [] person.errors.keys # => [:name]
# File activemodel/lib/active_model/errors.rb, line 180
def []=(attribute, error)
ActiveSupport::Deprecation.warn(" ActiveModel::Errors#[]= is deprecated and will be removed in Rails 5.1.
Use model.errors.add(:#{attribute}, #{error.inspect}) instead.
".squish)
messages[attribute.to_sym] << error
end Добавляет к указанному атрибуту указанное сообщение об ошибке.
person.errors[:name] = "must be set" person.errors[:name] # => ['must be set']
# File activemodel/lib/active_model/errors.rb, line 328
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 является proc, он будет вызван, что позволит использовать такие вещи, как 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 369
def add_on_blank(attributes, options = {})
ActiveSupport::Deprecation.warn(" ActiveModel::Errors#add_on_blank is deprecated and will be removed in Rails 5.1.
To achieve the same use:
errors.add(attribute, :blank, options) if value.blank?
".squish)
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"]}
# File activemodel/lib/active_model/errors.rb, line 347
def add_on_empty(attributes, options = {})
ActiveSupport::Deprecation.warn(" ActiveModel::Errors#add_on_empty is deprecated and will be removed in Rails 5.1.
To achieve the same use:
errors.add(attribute, :empty, options) if value.nil? || value.empty?
".squish)
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"]}
# File activemodel/lib/active_model/errors.rb, line 400
def added?(attribute, message = :invalid, options = {})
message = message.call if message.respond_to?(:call)
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 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 268 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"]}
# File activemodel/lib/active_model/errors.rb, line 101 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 153 def delete(key) details.delete(key) messages.delete(key) 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 204
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 242 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 438
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 416
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 431
def full_messages_for(attribute)
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 473
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 << :"#{@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
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 123
def get(key)
ActiveSupport::Deprecation.warn(" ActiveModel::Errors#get is deprecated and will be removed in Rails 5.1.
To achieve the same use model.errors[:#{key}].
".squish)
messages[key]
end Получить сообщения для key.
person.errors.messages # => {:name=>["cannot be nil"]}
person.errors.get(:name) # => ["cannot be nil"]
person.errors.get(:age) # => []
# File activemodel/lib/active_model/errors.rb, line 112 def include?(attribute) 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 233 def keys messages.keys end
Возвращает все ключи сообщений.
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.keys # => [:name]
# File activemodel/lib/active_model/errors.rb, line 138
def set(key, value)
ActiveSupport::Deprecation.warn(" ActiveModel::Errors#set is deprecated and will be removed in Rails 5.1.
Use model.errors.add(:#{key}, #{value.inspect}) instead.
".squish)
messages[key] = value
end Установить сообщения для key на value.
person.errors[:name] # => ["cannot be nil"] person.errors.set(:name, ["can't be nil"]) person.errors[:name] # => ["can't be nil"]
# File activemodel/lib/active_model/errors.rb, line 216 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 277
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
without_default_proc(self.messages)
end
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 258
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 225 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.