Class: Lobster::Serialization::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/lobster/serialization/serializer.rb

Overview

Transforms an object to and from its marshaled format. The marshaled form is a “simpler” object structure that can be written in JSON. This is the base serializer class. It converts the basic ruby types. To make a custom serializer for a new type, extend this class.

Instance Method Summary collapse

Instance Method Details

#add_to(engine) ⇒ nil

This method is abstract.

Adds the serializer to an engine.


17
18
19
# File 'lib/lobster/serialization/serializer.rb', line 17

def add_to(engine)
  fail NotImplementedError 'Must be overridden by sub-class'
end

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

Creates an object from its marshaled format.


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/lobster/serialization/serializer.rb', line 49

def deserialize(data, type, engine, *args)
  if type == Time
    fail FormatError unless data.is_a?(String)
    begin
      Time.parse(data)
    rescue ArgumentError
      fail FormatError
    end
  elsif type == Symbol
    fail FormatError unless data.is_a?(String)
    data.to_sym
  elsif type == Array
    fail FormatError unless data.is_a?(Array)
    data.map { |item| engine.deserialize_inner(item, item.class) }
  elsif type == Hash
    fail FormatError unless data.is_a?(Hash)
    Hash[ data.map { |key, value| [key.to_sym, engine.deserialize_inner(value, value.class)] } ]
  else
    fail FormatError unless data.is_a?(type)
    data
  end
end

#serialize(obj, engine) ⇒ Object

Note:

The default serialization for unknown is to call #to_s on the object.

Converts an object to its marshaled format.


29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/lobster/serialization/serializer.rb', line 29

def serialize(obj, engine)
  case obj
    when Fixnum, String, nil
      obj
    when Array
      obj.map { |item| engine.serialize_inner(item) }
    when Hash
      Hash[ obj.map { |key, value| [key.to_s, engine.serialize_inner(value)] } ]
    else
      obj.to_s
  end
end