Sha256: 205709de916c2e735b44cfb079c96f5b15d0dd386d4c33a92257abd2b890ea20

Contents?: true

Size: 1.42 KB

Versions: 36

Compression:

Stored size: 1.42 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.nil?
        value.to_i
      end

      def serialize(value)
        result = cast(value)
        if result
          ensure_in_range(result)
        end
        result
      end

      # TODO Change this to private once we've dropped Ruby 2.2 support.
      # Workaround for Ruby 2.2 "private attribute?" warning.
      protected

        attr_reader :range

      private

        def cast_value(value)
          case value
          when true then 1
          when false then 0
          else
            value.to_i rescue nil
          end
        end

        def ensure_in_range(value)
          unless range.cover?(value)
            raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes"
          end
        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

36 entries across 36 versions & 5 rubygems

Version Path
activemodel-5.2.8.1 lib/active_model/type/integer.rb
activemodel-5.2.8 lib/active_model/type/integer.rb
activemodel-5.2.7.1 lib/active_model/type/integer.rb
activemodel-5.2.7 lib/active_model/type/integer.rb
activemodel-5.2.6.3 lib/active_model/type/integer.rb
activemodel-5.2.6.2 lib/active_model/type/integer.rb
activemodel-5.2.6.1 lib/active_model/type/integer.rb
activemodel-5.2.6 lib/active_model/type/integer.rb
activemodel-5.2.4.6 lib/active_model/type/integer.rb
activemodel-5.2.5 lib/active_model/type/integer.rb
activemodel-5.2.4.5 lib/active_model/type/integer.rb
activemodel-5.2.4.4 lib/active_model/type/integer.rb
activemodel-5.2.4.3 lib/active_model/type/integer.rb
activemodel-5.2.4.2 lib/active_model/type/integer.rb
activemodel-5.2.4.1 lib/active_model/type/integer.rb
activemodel-5.2.4 lib/active_model/type/integer.rb
activemodel-5.2.4.rc1 lib/active_model/type/integer.rb
spiral_form-0.1.1 vendor/bundle/gems/activemodel-5.2.3/lib/active_model/type/integer.rb
spiral_form-0.1.0 vendor/bundle/gems/activemodel-5.2.3/lib/active_model/type/integer.rb
ric-0.13.0 vendor/bundle/ruby/2.5.0/gems/activemodel-5.2.3/lib/active_model/type/integer.rb