Skip to content

Commit 7c91bc0

Browse files
authored
Merge pull request #71 from jgaskins/fix-discriminator
Fix discriminator bug
2 parents b00b6d3 + 6989888 commit 7c91bc0

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

spec/serializable_spec.cr

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,12 @@ module Discriminator
359359
struct Updated < Message
360360
getter updated_at : Time
361361
end
362+
363+
# NOTE: not in the parent discriminator mapping
364+
struct Activity < Message
365+
getter type : String
366+
getter object : String
367+
end
362368
end
363369

364370
describe "MessagePack mapping" do
@@ -956,6 +962,15 @@ describe "MessagePack mapping" do
956962
updated.as(Discriminator::Updated).updated_at.should eq time
957963
end
958964

965+
it "allows subclasses not in discriminator mapping to be deserialized directly" do
966+
activity = Discriminator::Activity.from_msgpack({type: "Other", id: 456, object: "note:123"}.to_msgpack)
967+
968+
activity.should be_a Discriminator::Activity
969+
activity.type.should eq "Other"
970+
activity.id.should eq 456
971+
activity.object.should eq "note:123"
972+
end
973+
959974
describe "namespaced classes" do
960975
it "lets default values use the object's own namespace" do
961976
request = MessagePackNamespace::FooRequest.from_msgpack({foo: {} of String => String}.to_msgpack)

src/message_pack/serializable.cr

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,10 @@ module MessagePack
141141

142142
macro inherited
143143
def self.new(pull : ::MessagePack::Unpacker)
144-
super
144+
instance = allocate
145+
instance.initialize(__pull_for_msgpack_serializable: pull)
146+
GC.add_finalizer(instance) if instance.responds_to?(:finalize)
147+
instance
145148
end
146149
end
147150
end
@@ -268,7 +271,7 @@ module MessagePack
268271
{% key.raise "mapping keys must be one of StringLiteral, NumberLiteral, BoolLiteral, or Path, not #{key.class_name.id}" %}
269272
{% end %}
270273
{% end %}
271-
{{value.id}}.new(__pull_for_msgpack_serializable: MessagePack::NodeUnpacker.new(node))
274+
{{value.id}}.new(MessagePack::NodeUnpacker.new(node))
272275
{% end %}
273276
else
274277
raise ::MessagePack::UnpackError.new("Unknown '{{field.id}}' discriminator value: #{discriminator_value.inspect}", 0)

0 commit comments

Comments
 (0)