Skip to content

Commit e731a1d

Browse files
authored
MONGOID-5460 Update custom field type protocol documentation (#5441)
1 parent 5bfe737 commit e731a1d

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

docs/reference/fields.txt

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1127,11 +1127,25 @@ The ``demongoize`` method is used when calling the getters of fields for your cu
11271127
Note 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

11361150
Lastly, the class method ``evolve`` is similar to ``mongoize``, however it is used
11371151
when 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

Comments
 (0)