Class: Lobster::Network::MessageFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/lobster/network/message_factory.rb

Overview

Packs and unpacks messages from packets.

Instance Method Summary collapse

Constructor Details

#initializeMessageFactory

Returns a new instance of MessageFactory



18
19
20
21
22
23
24
25
26
# File 'lib/lobster/network/message_factory.rb', line 18

def initialize
  @engine = Lobster::Serialization::SerializationEngine.new
  Lobster::Serialization::UuidSerializer.new.add_to(@engine)
  Lobster::Serialization::ProfileSerializer.new.add_to(@engine)
  Lobster::Serialization::UserStatusSerializer.new.add_to(@engine)
  Lobster::Serialization::RoomSerializer.new.add_to(@engine)
  Lobster::Serialization::RoomThemeSerializer.new.add_to(@engine)
  MessageSerializer.new.add_to(@engine)
end

Instance Method Details

#pack(message) ⇒ Packet

Serializes a message and stores it in a packet.

Parameters:

  • message (Message)

    Message to serialize.

Returns:

  • (Packet)

    Packet containing the message.



31
32
33
34
35
36
# File 'lib/lobster/network/message_factory.rb', line 31

def pack(message)
  fail ArgumentError unless message.kind_of?(Message)

  packet_payload = @engine.serialize(message)
  Packet.new(packet_payload)
end

#unpack(packet, type = NilClass) ⇒ Message

Extracts a message from a packet.

Parameters:

  • packet (Packet)

    Packet containing the message.

  • type (Class) (defaults to: NilClass)

    Payload type to de-serialize.

Returns:

  • (Message)

    Message extracted from the packet.



42
43
44
45
46
47
48
# File 'lib/lobster/network/message_factory.rb', line 42

def unpack(packet, type = NilClass)
  fail ArgumentError unless packet.is_a?(Packet)

  # Pass the payload type to the serializer.
  # This way, the serializer knows how to handle the payload.
  @engine.deserialize(packet.payload, Message, type)
end