Sha256: eb60663220c4b7d9a6406d4b9b48fedf5a82256dae05c2b75cfde05cae5cb2dd

Contents?: true

Size: 1.13 KB

Versions: 7

Compression:

Stored size: 1.13 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Fields #:nodoc:
    module Serializable #:nodoc:

      # Defines the behaviour for integer fields.
      class Integer
        include Serializable

        # Serialize the object from the type defined in the model to a MongoDB
        # compatible object to store.
        #
        # @example Serialize the field.
        #   field.serialize(object)
        #
        # @param [ Object ] object The object to cast.
        #
        # @return [ Integer ] The converted integer.
        #
        # @since 2.1.0
        def serialize(object)
          return nil if object.blank?
          numeric(object) rescue object
        end

        private

        # Get the numeric value for the provided object.
        #
        # @example Get the numeric value.
        #   field.numeric("1120")
        #
        # @param [ Object ] object The object to convert.
        #
        # @return [ Integer, Float ] The number.
        #
        # @since 2.3.0
        def numeric(object)
          object.to_s =~ /(^[-+]?[0-9]+$)|(\.0+)$/ ? object.to_i : Float(object)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
mongoid-multi-db-3.0.0 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.5 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.4 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.3 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.2 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.1 lib/mongoid/fields/serializable/integer.rb
mongoid-2.3.0 lib/mongoid/fields/serializable/integer.rb