Class: Lobster::Network::MessageSerializer

Inherits:
Serialization::Serializer show all
Defined in:
lib/lobster/network/message_serializer.rb

Overview

Converts messages to and from their simplest object representation. This class is required in order to represent the message and its payload as a single JSON object.

Instance Method Summary collapse

Instance Method Details

#add_to(engine) ⇒ nil

This method is abstract.

Adds the serializer to an engine.

Parameters:

  • engine (SerializationEngine)

    Engine to add the serializer to.

Returns:

  • (nil)


17
18
19
# File 'lib/lobster/network/message_serializer.rb', line 17

def add_to(engine)
  engine.add_serializer(self, Lobster::Network::Message)
end

#deserialize(data, type, engine, *args) ⇒ Object

Creates a message from its marshaled format.

Parameters:

  • data (Object)

    Message in its marshaled format.

  • type (Class)

    Type of object that should be created.

  • engine (SerializationEngine)

    Engine performing the serialization. Use this to de-serialize the payload.

  • args

    Extra information that might be need for de-serializing.

Returns:

  • (Object)

    Newly created instance of the message representative of its marshaled format.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/lobster/network/message_serializer.rb', line 61

def deserialize(data, type, engine, *args)
  # The payload's type is the first extra argument.
  payload_type = args.first

  # Validate the structure of the message.
  validate_structure(data, {
                         :id      => Fixnum,
                         :name    => String,
                         :payload => args[0]
                         })

  # Get the common fields.
  id      = data[:id]
  name    = data[:name]
  payload = engine.deserialize_inner(data[:payload], payload_type)

  # Create the basic message or response message.
  if looks_like_response(data)
    request = data[:request]
    ResponseMessage.new(id, request, name, payload)
  else
    Message.new(id, name, payload)
  end
end

#serialize(obj, engine) ⇒ Object

Converts a message to its marshaled format.

Parameters:

  • obj (Message)

    Message to serialize.

  • engine (SerializationEngine)

    Engine performing the serialization. Use this to serialize the payload.

Returns:

  • (Object)

    Message marshaled to its simplest form.



26
27
28
29
30
# File 'lib/lobster/network/message_serializer.rb', line 26

def serialize(obj, engine)
  message_object = create_base_object(obj, engine)
  add_subtype_fields(obj, message_object)
  message_object
end