Sha256: ccbda43af6b9a0c96f84a0b3baf33439d447c6324766067784207c883e52b3fc

Contents?: true

Size: 1.13 KB

Versions: 22

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module ActiveModel
  module Type
    module Helpers # :nodoc: all
      module Numeric
        def serialize(value)
          cast(value)
        end

        def cast(value)
          value = \
            case value
            when true then 1
            when false then 0
            when ::String then value.presence
            else value
            end
          super(value)
        end

        def changed?(old_value, _new_value, new_value_before_type_cast) # :nodoc:
          super || number_to_non_number?(old_value, new_value_before_type_cast)
        end

        private
          def number_to_non_number?(old_value, new_value_before_type_cast)
            old_value != nil && non_numeric_string?(new_value_before_type_cast.to_s)
          end

          def non_numeric_string?(value)
            # 'wibble'.to_i will give zero, we want to make sure
            # that we aren't marking int zero to string zero as
            # changed.
            !NUMERIC_REGEX.match?(value)
          end

          NUMERIC_REGEX = /\A\s*[+-]?\d/
          private_constant :NUMERIC_REGEX
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
activemodel-6.0.6.1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.6 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.5.1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.5 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.8 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.7 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.6 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.5 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.4 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.3 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.2 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4.1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.4 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.7 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.6 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.5 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.4 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.3 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.2 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.3.1 lib/active_model/type/helpers/numeric.rb