跳到內容 跳到搜尋

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?(屬性, 類型 = nil, **選項)

查看錯誤是否與提供的屬性類型選項相符。

未包含的參數不會檢查是否相符。

# 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?(屬性, 類型, **選項)

查看錯誤是否與提供的屬性類型選項完全相符。

所有參數都必須等於錯誤本身的屬性,才會被視為嚴格相符。

# 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