跳至內容 跳至搜尋

Active Model 值類型

所有屬性類型的基礎類別。這個類別也作為未指定類型的屬性的預設類型。

方法
#
A
C
D
E
H
N
S
T
包含模組

屬性

[R] limit
[R] precision
[R] scale

類別公開方法

new(precision: nil, limit: nil, scale: nil)

使用三個基本組態設定來初始化類型:精確度、限制和比例。[值]Value基礎類別未定義這些設定的行為。它只使用這些設定進行相等比較和雜湊金鑰產生。

# File activemodel/lib/active_model/type/value.rb, line 17
def initialize(precision: nil, limit: nil, scale: nil)
  super()
  @precision = precision
  @scale = scale
  @limit = limit
end

執行個體公開方法

==(other)

別名也為: eql?
# File activemodel/lib/active_model/type/value.rb, line 121
def ==(other)
  self.class == other.class &&
    precision == other.precision &&
    scale == other.scale &&
    limit == other.limit
end

as_json(*)

# File activemodel/lib/active_model/type/value.rb, line 144
def as_json(*)
  raise NoMethodError
end

assert_valid_value(_)

# File activemodel/lib/active_model/type/value.rb, line 133
def assert_valid_value(_)
end

cast(value)

[類型]Type會將值從使用者輸入轉換(例如從設定程式)。此值可能是來自表單生成器的字串,或傳遞至設定程式的紅寶石物件。目前無法區分來源為何。

此方法的傳回值會從 ActiveRecord::AttributeMethods::Read#read_attribute 傳回。另請參閱: Value#cast_value

value傳送至屬性設定程式的未處理輸入。

# File activemodel/lib/active_model/type/value.rb, line 57
def cast(value)
  cast_value(value) unless value.nil?
end

changed?(old_value, new_value, _new_value_before_type_cast)

判定值是否已針對 dirty checking 進行變更。old_valuenew_value 會一直轉換為型態。類型不應需要覆寫這個方法。

# File activemodel/lib/active_model/type/value.rb, line 84
def changed?(old_value, new_value, _new_value_before_type_cast)
  old_value != new_value
end

changed_in_place?(raw_old_value, new_value)

判定可變動值在被讀取後是否已修改。預設傳回 false。如果你的型態傳回一個可變動的物件,你應覆寫這個方法。你需要

或者

raw_old_value 在傳遞給 deserialize 之前的原始值。

new_value 轉換型態後的目前值。

# File activemodel/lib/active_model/type/value.rb, line 105
def changed_in_place?(raw_old_value, new_value)
  false
end

deserialize(value)

將資料庫輸入值轉換為適當的 Ruby 型態。此方法的傳回值會從 ActiveRecord::AttributeMethods::Read#read_attribute 傳回。預設實作僅呼叫 Value#cast

value 資料庫提供的原始輸入。

# File activemodel/lib/active_model/type/value.rb, line 43
def deserialize(value)
  cast(value)
end

eql?(other)

別名:==

hash()

# File activemodel/lib/active_model/type/value.rb, line 129
def hash
  [self.class, precision, scale, limit].hash
end

serializable?(value)

如果此型態可以將 value 轉換為資料庫可用的型態,則傳回 true。例如布林型態如果值參數為 Ruby 布林,則可傳回 true,但如果值參數是其他物件,則可能傳回 false

# File activemodel/lib/active_model/type/value.rb, line 28
def serializable?(value)
  true
end

serialize(value)

將 Ruby 型態的值轉換為資料庫可以理解的型態。此方法的傳回值應為 StringNumericDateTimeSymboltruefalsenil

# File activemodel/lib/active_model/type/value.rb, line 65
def serialize(value)
  value
end

type()

將唯一類型名稱傳回為 符號。子類別應覆寫此方法。

# File activemodel/lib/active_model/type/value.rb, line 34
def type
end

實例私人方法

cast_value(value)

對於不需要為使用者和資料庫輸入進行個別類型轉換行為的類型而言,這是一個簡便的方法。由 Value#cast 函式呼叫,以處理除 nil 之外的值。

# File activemodel/lib/active_model/type/value.rb, line 152
def cast_value(value) # :doc:
  value
end