跳至内容 跳至搜索

Active Model 错误

表示单个错误

方法
A
D
F
M
N
S

常量

CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
 
MESSAGE_OPTIONS = [:message]
 

属性

[R] attribute

错误所属的base的属性

[R] base

错误所属的对象

[R] options

调用errors#add时提供的选项

[R] raw_type

调用errors#add时作为第二个参数提供的原始值

[R] type

错误类型,除非指定,否则默认为:invalid

类公共方法

new(base, attribute, type = :invalid, **options)

# File activemodel/lib/active_model/error.rb, line 103
def initialize(base, attribute, type = :invalid, **options)
  @base = base
  @attribute = attribute
  @raw_type = type
  @type = type || :invalid
  @options = options
end

实例公共方法

detail()

别名: details

details()

返回错误详细信息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.details
# => { error: :too_short, count: 5 }
别名: detail
# File activemodel/lib/active_model/error.rb, line 149
def details
  { error: raw_type }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS))
end

full_message()

返回完整的错误信息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.full_message
# => "Name is too short (minimum is 5 characters)"
# File activemodel/lib/active_model/error.rb, line 159
def full_message
  self.class.full_message(attribute, message, @base)
end

match?(attribute, type = nil, **options)

查看错误是否与提供的attributetypeoptions匹配。

未包含的参数不会被检查是否匹配。

# File activemodel/lib/active_model/error.rb, line 166
def match?(attribute, type = nil, **options)
  if @attribute != attribute || (type && @type != type)
    return false
  end

  options.each do |key, value|
    if @options[key] != value
      return false
    end
  end

  true
end

message()

返回错误消息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.message
# => "is too short (minimum is 5 characters)"
# File activemodel/lib/active_model/error.rb, line 135
def message
  case raw_type
  when Symbol
    self.class.generate_message(attribute, raw_type, @base, options.except(*CALLBACKS_OPTIONS))
  else
    raw_type
  end
end

strict_match?(attribute, type, **options)

查看错误是否与提供的attributetypeoptions完全匹配。

所有参数都必须等于 Error 自身的属性,才被视为严格匹配。

# File activemodel/lib/active_model/error.rb, line 184
def strict_match?(attribute, type, **options)
  return false unless match?(attribute, type)

  options == @options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)
end

实例保护的方法

attributes_for_hash()

# File activemodel/lib/active_model/error.rb, line 204
def attributes_for_hash
  [@base, @attribute, @raw_type, @options.except(*CALLBACKS_OPTIONS)]
end