-
Type: Improvement
-
Resolution: Fixed
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: BSON
-
None
-
Fully Compatible
BSON::Document performs value conversion in []=. This means the following pattern often does not produce intended results:
def foo # @doc is a BSON::Document @doc[:foo] ||= calculation end
While this code intends to return doc[:foo] to the caller, it actually returns the result of calculation which may be a different object from the one stored in @doc. If the application later modifies the return value of this method, data stored in @doc won't be affected. This was reported in https://github.com/mongodb/bson-ruby/pull/121.
The correct pattern to use is the following, where the key is read out of the document following the write:
def foo # @doc is a BSON::Document @doc[:foo] ||= calculation and @doc[:foo] end
Since this behavior is dictated by Ruby, I don't see what we can do to repair it in the sense of the original pattern working as expected by the users.