Uploaded image for project: 'Ruby Driver'
  1. Ruby Driver
  2. RUBY-1979

Document return value of []= caveat

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • bson-4.6.0
    • 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.

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: