Sha256: 848829b1aad49ac8204220ad9a5d2c1e41ca061d6fffa83a5791d1514999aacf

Contents?: true

Size: 1007 Bytes

Versions: 28

Compression:

Stored size: 1007 Bytes

Contents

# frozen_string_literal: true

module ActiveModel
  module Type
    module Helpers # :nodoc: all
      module Numeric
        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)
          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.
            !/\A[-+]?\d+/.match?(value.to_s)
          end
      end
    end
  end
end

Version data entries

28 entries across 28 versions & 4 rubygems

Version Path
ric-0.12.2 vendor/bundle/ruby/2.5.0/gems/activemodel-5.2.3/lib/active_model/type/helpers/numeric.rb
activemodel-5.2.3 lib/active_model/type/helpers/numeric.rb
activemodel-5.2.3.rc1 lib/active_model/type/helpers/numeric.rb
activemodel-5.2.2.1 lib/active_model/type/helpers/numeric.rb
activemodel-6.0.0.beta1 lib/active_model/type/helpers/numeric.rb
nullifyable-0.1.0 vendor/bundle/gems/activemodel-5.2.2/lib/active_model/type/helpers/numeric.rb
activemodel-5.2.2 lib/active_model/type/helpers/numeric.rb
activemodel-5.2.2.rc1 lib/active_model/type/helpers/numeric.rb