Class: Typed::MessagePackSerializer

Inherits:
Serializer show all
Defined in:
lib/typed/message_pack_serializer.rb

Constant Summary collapse

Input =

MessagePack packs to a binary (ASCII-8BIT) encoded string, not text, but String is still the correct Sorbet type for it, same as Input/Output on the other serializers.

type_member { {fixed: String} }
Output =
type_member { {fixed: String} }

Constants inherited from Serializer

Serializer::DeserializeResult, Serializer::Params

Instance Attribute Summary

Attributes inherited from Serializer

#coercer_cache, #schema

Instance Method Summary collapse

Constructor Details

#initialize(schema:) ⇒ MessagePackSerializer

Returns a new instance of MessagePackSerializer.



12
13
14
15
16
17
# File 'lib/typed/message_pack_serializer.rb', line 12

def initialize(schema:)
  require "msgpack"
  super
rescue LoadError
  raise ArgumentError, "msgpack gem is required for MessagePack serialization - add it to your Gemfile"
end

Instance Method Details

#deserialize(source) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/typed/message_pack_serializer.rb', line 20

def deserialize(source)
  parsed_msgpack = MessagePack.unpack(source)
  return Failure.new(ParseError.new(format: :msgpack)) unless parsed_msgpack.is_a?(Hash)

  creation_params = schema.fields.each_with_object(T.let({}, Params)) do |field, hsh|
    hsh[field.name] = parsed_msgpack[field.name.to_s]
  end

  deserialize_from_creation_params(creation_params)
rescue MessagePack::UnpackError, EOFError
  Failure.new(ParseError.new(format: :msgpack))
end

#serialize(struct) ⇒ Object



34
35
36
37
38
# File 'lib/typed/message_pack_serializer.rb', line 34

def serialize(struct)
  return Failure.new(SerializeError.new("'#{struct.class}' cannot be serialized to target type of '#{schema.target}'.")) if struct.class != schema.target

  Success.new(MessagePack.pack(serialize_from_struct(struct:, should_serialize_values: true)))
end