Skip to content

Commit

Permalink
add support for legacy deserialization
Browse files Browse the repository at this point in the history
Mongoid specs, for instance, rely on BSON::Binary defining only two
instance variables, and build testing data around that assumption.
  • Loading branch information
jamis committed Nov 30, 2023
1 parent ea6fe69 commit f46e1c7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 11 additions & 1 deletion lib/bson/binary.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,17 @@ def as_extended_json(**options)
#
# @since 2.0.0
def initialize(data = '', type = :generic)
@type = validate_type!(type)
init_with('data' => data, 'type' => type)
end

# For legacy deserialization support where BSON::Binary objects are
# expected to have a specific internal representation (with only
# @type and @data instance variables).
#
# @api private
def init_with(coder)
@type = validate_type!(coder['type'])
data = coder['data']

# The Binary class used to force encoding to BINARY when serializing to
# BSON. Instead of doing that during serialization, perform this
Expand Down
11 changes: 10 additions & 1 deletion spec/bson/binary_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
end
end

context "when he type is invalid" do
context "when the type is invalid" do

it "raises an error" do
expect {
Expand All @@ -93,6 +93,15 @@
}
end
end

context 'when initialized via legacy YAML' do
let(:yaml) { "--- !ruby/object:BSON::Binary\ndata: hello\ntype: :generic\n" }
let(:deserialized) { YAML.safe_load(yaml, permitted_classes: [ Symbol, BSON::Binary ]) }

it 'correctly sets the raw_type' do
expect(deserialized.raw_type).to be == BSON::Binary::SUBTYPES[:generic]
end
end
end

describe '#inspect' do
Expand Down

0 comments on commit f46e1c7

Please sign in to comment.