Skip to content

annotation Athena::Serializer::Annotations::Discriminator #

Allows deserializing an object based on the value of a specific field.

Fields#

  • key : String - The field that should be read from the data to determine the correct type.
  • map : Hash | NamedTuple - Maps the possible key values to their corresponding types.

Example#

@[ASRA::Discriminator(key: "type", map: {point: Point, circle: Circle})]
abstract class Shape
  include ASR::Serializable

  property type : String
end

class Point < Shape
  property x : Int32
  property y : Int32
end

class Circle < Shape
  property x : Int32
  property y : Int32
  property radius : Int32
end

ASR.serializer.deserialize Shape, %({"type":"point","x":10,"y":20}), :json              # => #<Point:0x7fbbf7f8bc20 @type="point", @x=10, @y=20>
ASR.serializer.deserialize Shape, %({"type":"circle","x":30,"y":40,"radius":12}), :json # => #<Circle:0x7fbbf7f93c60 @radius=12, @type="circle", @x=30, @y=40>