Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/mongoid/extensions.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'mongoid/extensions/array'
require 'mongoid/extensions/bson_document'
require 'mongoid/extensions/big_decimal'
require 'mongoid/extensions/binary'
require 'mongoid/extensions/boolean'
Expand Down
28 changes: 28 additions & 0 deletions lib/mongoid/extensions/bson_document.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

module Mongoid
module Extensions
# Adds behavior to BSON::Document.
module BsonDocument
# Make a deep copy of this document, preserving the BSON::Document type.
#
# Hash#__deep_copy__ returns a plain Hash, which causes field_was to
# return a different type than the field getter when the stored attribute
# is a BSON::Document.
#
# @example Make a deep copy of the document.
# doc.__deep_copy__
#
# @return [ BSON::Document ] The copied document.
def __deep_copy__
self.class.new.tap do |copy|
each_pair do |key, value|
copy.store(key, value.__deep_copy__)
end
end
end
end
end
end

BSON::Document.include Mongoid::Extensions::BsonDocument
18 changes: 18 additions & 0 deletions spec/mongoid/changeable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,24 @@
expect(person.send(:attribute_was, 'title')).to eq('Grand Poobah')
end
end

context 'when the attribute is a Hash field stored as a BSON::Document' do
let(:person) do
Person.new(map: BSON::Document.new('foo' => true)).tap(&:move_changes)
end

Comment thread
jamis marked this conversation as resolved.
before do
person.map['bar'] = true
end

it 'returns a BSON::Document, consistent with the field getter' do
expect(person.map_was).to be_a(BSON::Document)
end

it 'returns the correct previous value' do
expect(person.map_was).to eq('foo' => true)
end
end
end

describe '#attribute_previously_was' do
Expand Down
Loading