略過至內文 略過至搜尋

Active Model 浮點值類型

用於浮點數值屬性類型。它會註冊至 :float

class BagOfCoffee
  include ActiveModel::Attributes

  attribute :weight, :float
end

會使用 to_f 方法轉換值,但下列字串除外

  • 空白字串會轉換至 nil

  • "Infinity" 會轉換至 Float::INFINITY

  • "-Infinity" 會轉換至 -Float::INFINITY

  • "NaN" 會轉換至 Float::NAN

    bag = BagOfCoffee.new

    bag.weight = “0.25” bag.weight # => 0.25

    bag.weight = “” bag.weight # => nil

    bag.weight = “NaN” bag.weight # => Float::NAN

方法
T
包含的模組

執行個體公用方法

type()

# File activemodel/lib/active_model/type/float.rb, line 39
def type
  :float
end

type_cast_for_schema(value)

# File activemodel/lib/active_model/type/float.rb, line 43
def type_cast_for_schema(value)
  return "::Float::NAN" if value.try(:nan?)
  case value
  when ::Float::INFINITY then "::Float::INFINITY"
  when -::Float::INFINITY then "-::Float::INFINITY"
  else super
  end
end