Sha256: 865d9ee30f3339abef6153c209e22510733498213c5d529b2424961cfb3482f9

Contents?: true

Size: 1.55 KB

Versions: 42

Compression:

Stored size: 1.55 KB

Contents

# frozen_string_literal: true

require "active_support/core_ext/object/try"

module ActiveModel
  module Type
    # = Active Model \Float \Type
    #
    # Attribute type for floating point numeric values. It is registered under
    # the +:float+ key.
    #
    #   class BagOfCoffee
    #     include ActiveModel::Attributes
    #
    #     attribute :weight, :float
    #   end
    #
    # Values are cast using their +to_f+ method, except for the following
    # strings:
    #
    # - Blank strings are cast to +nil+.
    # - <tt>"Infinity"</tt> is cast to +Float::INFINITY+.
    # - <tt>"-Infinity"</tt> is cast to <tt>-Float::INFINITY</tt>.
    # - <tt>"NaN"</tt> is cast to +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
    class Float < Value
      include Helpers::Numeric

      def type
        :float
      end

      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

      private
        def cast_value(value)
          case value
          when ::Float then value
          when "Infinity" then ::Float::INFINITY
          when "-Infinity" then -::Float::INFINITY
          when "NaN" then ::Float::NAN
          else value.to_f
          end
        end
    end
  end
end

Version data entries

42 entries across 42 versions & 6 rubygems

Version Path
minato_ruby_api_client-0.2.2 vendor/bundle/ruby/3.2.0/gems/activemodel-7.1.3.4/lib/active_model/type/float.rb
activemodel-8.0.1 lib/active_model/type/float.rb
activemodel-8.0.0.1 lib/active_model/type/float.rb
activemodel-7.2.2.1 lib/active_model/type/float.rb
activemodel-7.1.5.1 lib/active_model/type/float.rb
activemodel-8.0.0 lib/active_model/type/float.rb
activemodel-7.2.2 lib/active_model/type/float.rb
activemodel-7.1.5 lib/active_model/type/float.rb
activemodel-8.0.0.rc2 lib/active_model/type/float.rb
activemodel-7.2.1.2 lib/active_model/type/float.rb
activemodel-7.1.4.2 lib/active_model/type/float.rb
activemodel-8.0.0.rc1 lib/active_model/type/float.rb
activemodel-7.2.1.1 lib/active_model/type/float.rb
activemodel-7.1.4.1 lib/active_model/type/float.rb
activemodel-8.0.0.beta1 lib/active_model/type/float.rb
omg-activemodel-8.0.0.alpha9 lib/active_model/type/float.rb
omg-activemodel-8.0.0.alpha8 lib/active_model/type/float.rb
omg-activemodel-8.0.0.alpha7 lib/active_model/type/float.rb
omg-activemodel-8.0.0.alpha4 lib/active_model/type/float.rb
omg-activemodel-8.0.0.alpha3 lib/active_model/type/float.rb