Sha256: 8a7047551e4efb720f4f5d32a0d6e2e0b00cabf512f46201d9ee332bd9d22826

Contents?: true

Size: 1.37 KB

Versions: 41

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module ActiveModel
  module Type
    class Integer < Value # :nodoc:
      include Helpers::Numeric

      # Column storage size in bytes.
      # 4 bytes means an integer as opposed to smallint etc.
      DEFAULT_LIMIT = 4

      def initialize(**)
        super
        @range = min_value...max_value
      end

      def type
        :integer
      end

      def deserialize(value)
        return if value.blank?
        value.to_i
      end

      def serialize(value)
        return if value.is_a?(::String) && non_numeric_string?(value)
        ensure_in_range(super)
      end

      def serializable?(value)
        cast_value = cast(value)
        in_range?(cast_value) && super
      end

      private
        attr_reader :range

        def in_range?(value)
          !value || range.member?(value)
        end

        def cast_value(value)
          value.to_i rescue nil
        end

        def ensure_in_range(value)
          unless in_range?(value)
            raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes"
          end
          value
        end

        def max_value
          1 << (_limit * 8 - 1) # 8 bits per byte with one bit for sign
        end

        def min_value
          -max_value
        end

        def _limit
          limit || DEFAULT_LIMIT
        end
    end
  end
end

Version data entries

41 entries across 41 versions & 6 rubygems

Version Path
activemodel-6.1.7.10 lib/active_model/type/integer.rb
activemodel-6.1.7.9 lib/active_model/type/integer.rb
activemodel-6.1.7.8 lib/active_model/type/integer.rb
activemodel-6.1.7.7 lib/active_model/type/integer.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/activemodel-6.1.6.1/lib/active_model/type/integer.rb
activemodel-6.1.7.6 lib/active_model/type/integer.rb
activemodel-6.1.7.5 lib/active_model/type/integer.rb
activemodel-6.1.7.4 lib/active_model/type/integer.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/activemodel-6.1.6.1/lib/active_model/type/integer.rb
activemodel-6.1.7.3 lib/active_model/type/integer.rb
activemodel-6.1.7.2 lib/active_model/type/integer.rb
activemodel-6.1.7.1 lib/active_model/type/integer.rb
activemodel-6.1.7 lib/active_model/type/integer.rb
activemodel-6.1.6.1 lib/active_model/type/integer.rb
activemodel-6.1.6 lib/active_model/type/integer.rb
activemodel-6.1.5.1 lib/active_model/type/integer.rb
activemodel-6.1.5 lib/active_model/type/integer.rb
activemodel-6.1.4.7 lib/active_model/type/integer.rb
activemodel-6.1.4.6 lib/active_model/type/integer.rb
activemodel-6.1.4.5 lib/active_model/type/integer.rb