module Serializable::Object

Defined in:

db.cr
json.cr
msgpack.cr
object.cr

Constructors

Macro Summary

Instance Method Summary

Constructor Detail

def self.new(*, with_db_result_set rs : DB::ResultSet) #

[View source]
def self.new(*, with_json_pull_parser pull : ::JSON::PullParser) #

[View source]
def self.new(*, with_msgpack_unpacker pull : MessagePack::Unpacker) #

[View source]

Macro Detail

macro use_json_discriminator(field, mapping) #

Tells this class to decode JSON by using a field as a discriminator.

  • field must be the field name to use as a discriminator
  • mapping must be a hash or named tuple where each key-value pair maps a discriminator value to a class to deserialize

For example:

require "json"

abstract class Shape
  include JSON::Serializable

  use_json_discriminator "type", {point: Point, circle: Circle}

  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

Shape.from_json(%({"type": "point", "x": 1, "y": 2}))               # => #<Point:0x10373ae20 @type="point", @x=1, @y=2>
Shape.from_json(%({"type": "circle", "x": 1, "y": 2, "radius": 3})) # => #<Circle:0x106a4cea0 @type="circle", @x=1, @y=2, @radius=3>

[View source]
macro use_msgpack_discriminator(field, mapping) #

[View source]

Instance Method Detail

def to_json(json : ::JSON::Builder) #

[View source]
def to_msgpack(packer : MessagePack::Packer) #

[View source]