作用中模型整數類型
適用於整數表示形式的屬性類型。此類型於 :integer
金鑰下註冊。
class Person
include ActiveModel::Attributes
attribute :age, :integer
end
使用其 to_i
方法轉換值,空白字串除外,因為空白字串會轉換成 nil
。如果沒有定義 to_i
方法或引發錯誤,該值將會轉換成 nil
。
person = Person.new
person.age = "18"
person.age # => 18
person.age = ""
person.age # => nil
person.age = :not_an_integer
person.age # => nil (because Symbol does not define #to_i)
序列處理
採用相同原理。例如,非數值字串會序列化為 nil
。
序列處理
還要驗證整數是否能夠使用有限位元組儲存。如果無法,則會引發 ActiveModel::RangeError
。預設限制為 4 個位元組,可在宣告屬性時客製化。
class Person
include ActiveModel::Attributes
attribute :age, :integer, limit: 6
end
方法
包含的模組
常數
DEFAULT_LIMIT | = | 4 |
資料庫欄位儲存大小(以位元組為單位)。4 個位元組表示一個整數,與 shortint 等不同。 |
類別公開方法
new(**) 連結
Source: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/type/integer.rb, line 51 def initialize(**) super @range = min_value...max_value end
個體公開方法
反序列處理(value) 連結
Source: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/type/integer.rb, line 60 def deserialize(value) return if value.blank? value.to_i end
可序列化嗎?(value) 連結
Source: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/type/integer.rb, line 74 def serializable?(value) cast_value = cast(value) in_range?(cast_value) || begin yield cast_value if block_given? false end end
序列化(value) 連結
Source: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/type/integer.rb, line 65 def serialize(value) return if value.is_a?(::String) && non_numeric_string?(value) ensure_in_range(super) end
類型() 連結
Source: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/type/integer.rb, line 56 def type :integer end