mongoid/mongoid — Issue #1604: Confusion regarding Mongoid::Fields::Serializable
Author: mkscrg
Created: 2012-01-18 00:31:53+00:00
State: open

I'm not sure whether this is a bug or just a documentation problem, but either way it would seem to be an "issue".

The documentation at gives this as the example of custom field serialization:

class Profile
include Mongoid::Document
field :location, type: Point
end

class Point
include Mongoid::Fields::Serializable

def deserialize(object)
[ object["x"], object["y"] ]
end

def serialize(object)
{ "x" => object[0], "y" => object[1] }
end
end

What follows is my understanding of this example, and the questions that follow from it.

The line `field :location, type: Point` says that the `.location` attribute of each `Profile` object should be a `Point` object. So when you call `a_profile.location`, you should get some value `a_point` such that `a_point.class == Point`. Furthermore, the `deserialize` method should map from a `Hash` (or whatever special version of `Hash` the mongo driver spits out) to a `Point`, and the `serialize` method should do the opposite.

Assuming that's true, a couple questions come up:

1. Why is `deserialize` an instance method of `Point`? What instance of `Point` is `deserialized` called on? Shouldn't it be a class method of `Point`? And why does `deserialize` return an `Array`, rather than a `Point`?
2. Likewise, why does `serialize` take the parameter `object`? Since it's a instance method of `Point` and it maps the `Point` to a `Hash`, should `object` be `self`?

Clearly, I have the wrong idea about how custom field serialization is modeled in Mongoid. Can someone elaborate what's actually going on here?

Cheers,
Mike