@@ -1127,11 +1127,25 @@ The ``demongoize`` method is used when calling the getters of fields for your cu
11271127Note that in the example above, since ``demongoize`` calls ``Point.new``, a new instance of
11281128``Point`` will be generated on each call to the getter.
11291129
1130- .. note::
1130+ Mongoid will always call the ``demongoize`` method on values that were
1131+ retrieved from the database, but applications may, in theory, call
1132+ ``demongoize`` with arbitrary input. It is recommended that applications add
1133+ handling for arbitrary input in their ``demongoize`` methods. We can rewrite
1134+ ``Point``'s demongoize method as follows:
11311135
1132- The ``mongoize`` and ``demongoize`` methods should return ``nil`` on values
1133- that are uncastable to your custom type. See the section on :ref:`Uncastable
1134- Values <uncastable-values>` for more details.
1136+ .. code:: ruby
1137+
1138+ def demongoize(object)
1139+ if object.is_a?(Array) && object.length == 2
1140+ Point.new(object[0], object[1])
1141+ end
1142+ end
1143+
1144+ Notice that ``demongoize`` will only create a new ``Point`` if given an array
1145+ of length 2, and will return ``nil`` otherwise. Both the ``mongoize`` and
1146+ ``demongoize`` methods should be prepared to receive arbitrary input and should
1147+ return ``nil`` on values that are uncastable to your custom type. See the
1148+ section on :ref:`Uncastable Values <uncastable-values>` for more details.
11351149
11361150Lastly, the class method ``evolve`` is similar to ``mongoize``, however it is used
11371151when transforming objects for use in Mongoid query criteria.
@@ -1141,6 +1155,11 @@ when transforming objects for use in Mongoid query criteria.
11411155 point = Point.new(12, 24)
11421156 Venue.where(location: point) # This uses Point.evolve
11431157
1158+ The ``evolve`` method should also be prepared to receive arbitrary input,
1159+ however, unlike the ``mongoize`` and ``demongoize`` methods, it should return
1160+ the inputted value on values that are uncastable to your custom type. See the
1161+ section on :ref:`Uncastable Values <uncastable-values>` for more details.
1162+
11441163
11451164.. _phantom-custom-field-types:
11461165
0 commit comments