Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-933

Field Casting of type Integer

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.3.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      Scenario 1:

      Given I have a field with type Integer.
      When I update the value of that field to '08'
      Then the value is saved in the database as a string

      Scenario 2:

      Given I have a field with type Integer.
      When I update the value of that field to '011'
      Then the value is saved in the database as 9 (integer)

      Observation

      reason I've found is in the file: mongoid / lib / mongoid / extensions / integer / conversions.rb

      # encoding: utf-8
      module Mongoid #:nodoc:
        module Extensions #:nodoc:
          module Integer #:nodoc:
            module Conversions #:nodoc:
              def set(value)
                return nil if value.blank?
                begin
                  value.to_s =~ /\./ ? Float(value) : Integer(value)
                rescue
                  value
                end
              end
              def get(value)
                value
              end
            end
          end
        end
      end
      

      For Scenario 1:

      It attempts to pass Integer(value) if that does not work it raises an exception which is rescued and returns the string representation.

      For Scenario 2:

      It calls Integer(value) which by documentation does the following:

      > If arg is a String, when base is omitted or equals to zero,
      > radix indicators (0, 0b, and 0x) are honored. In any
      > case, strings should be strictly conformed to numeric representation.
      > This behavior is different from that of String#to_i. Non string
      > values will be converted using to_int, and to_i.

            Assignee:
            Unassigned Unassigned
            Reporter:
            coffeencoke Matt Simpson
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: