跳至内容 跳至搜索

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