@@ -1127,11 +1127,25 @@ The ``demongoize`` method is used when calling the getters of fields for your cu
1127
1127
Note that in the example above, since ``demongoize`` calls ``Point.new``, a new instance of
1128
1128
``Point`` will be generated on each call to the getter.
1129
1129
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:
1131
1135
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.
1135
1149
1136
1150
Lastly, the class method ``evolve`` is similar to ``mongoize``, however it is used
1137
1151
when transforming objects for use in Mongoid query criteria.
@@ -1141,6 +1155,11 @@ when transforming objects for use in Mongoid query criteria.
1141
1155
point = Point.new(12, 24)
1142
1156
Venue.where(location: point) # This uses Point.evolve
1143
1157
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
+
1144
1163
1145
1164
.. _phantom-custom-field-types:
1146
1165
0 commit comments