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

Custom field value serializer not working?

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

      Following the docs at http://mongoid.org/en/mongoid/docs/documents.html regarding custom field serialization, I came up with a type class. But it seems as though none of the serialization methods are being called.

      See the following test case. I expect the value stored in the bar field to have an exclamation mark appended to it per the #mongoize implementation. That's not happening, so I can surmise that the mongoize method isn't being called.

      I can't tell if this is a documentation problem, a bug, or more likely something I'm doing wrong...

      require 'test/unit'
      require 'mongoid'
      
      class TestType < Test::Unit::TestCase
        def test_value_mongoized
          foo = Foo.create(bar: 'baz')
          assert_equal 'baz!', Foo.collection.find({_id: foo.id}).first['bar']
        end
      end
      
      Mongoid.sessions =  { default: { database: 'test', hosts: ['localhost:27017'] } }
      
      #
      # Custom field type 
      #
      class Baz
        attr_reader :val
      
        def initialize(val)
          @val= val
        end
      
        # Add an exclamation mark to serialized value
        def mongoize
          "#{val}!"
        end
        
        # Remove exclamation mark from serialized value
        class << self
          def demongoize(obj)
            Baz.new(obj.gsub('!', ''))
          end
      
          def evolve(obj)
            if obj.is_a?(Baz)
              obj.val
            else
              obj
            end
          end
        end
      end
      
      #
      # Mongoid Document
      #
      class Foo
        include Mongoid::Document
        field :bar, type: Baz
      end
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            alexkwolfe Alex Wolfe
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: