Sha256: 8aa603428dccb682daa57f7486b3dcb5e6efee377a9edc171a464367dc4318c9

Contents?: true

Size: 1.13 KB

Versions: 16

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

16 entries across 16 versions & 4 rubygems

Version Path
activemodel-6.0.2.2 lib/active_model/type/helpers/numeric.rb
argon-1.3.1 vendor/bundle/ruby/2.7.0/gems/activemodel-6.0.2.1/lib/active_model/type/helpers/numeric.rb
symbolic_enum-1.1.5 vendor/bundle/ruby/2.7.0/gems/activemodel-6.0.2.1/lib/active_model/type/helpers/numeric.rb
activemodel-6.0.2.1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.2 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.2.rc2 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.2.rc1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.1 lib/active_model/type/helpers/numeric.rb
chatops-rpc-0.0.2 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/activemodel-6.0.0/lib/active_model/type/helpers/numeric.rb
activemodel-6.0.1.rc1 lib/active_model/type/helpers/numeric.rb
chatops-rpc-0.0.1 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/activemodel-6.0.0/lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0.rc2 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0.rc1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0.beta3 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0.beta2 lib/active_model/type/helpers/numeric.rb