Module: Cuboid::RPC::Serializer

Extended by:
Serializer
Included in:
Serializer
Defined in:
lib/cuboid/rpc/serializer.rb

Overview

Used for serialization of Cuboid::RPC messages.

It’s simply a delegator for ‘MessagePack` with `Zlib` compression for messages that are larger than COMPRESS_LARGER_THAN.

Constant Summary collapse

COMPRESS_LARGER_THAN =

Compress object dumps larger than 1KB.

1_000

Instance Method Summary collapse

Instance Method Details

#compress(string) ⇒ String

Note:

Ignores strings smaller than #COMPRESS_LARGER_THAN.

Returns Compressed (or not) ‘string`.



59
60
61
62
# File 'lib/cuboid/rpc/serializer.rb', line 59

def compress( string )
    return string if string.size < COMPRESS_LARGER_THAN
    Zlib::Deflate.deflate string
end

#decompress(string) ⇒ String

Note:

Will return the ‘string` as is if it was not compressed.

Returns Decompressed string.



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/cuboid/rpc/serializer.rb', line 71

def decompress( string )
    return '' if string.to_s.empty?

    # Just an ID representing a serialized, empty data structure.
    return string if string.size == 1

    begin
        Zlib::Inflate.inflate string
    rescue Zlib::DataError
        string
    end
end

#deep_clone(object) ⇒ Object



48
49
50
# File 'lib/cuboid/rpc/serializer.rb', line 48

def deep_clone( object )
    object.class.from_rpc_data rpc_data( object )
end

#dump(object) ⇒ String



21
22
23
24
# File 'lib/cuboid/rpc/serializer.rb', line 21

def dump( object )
    # ap object
    compress( serializer.dump( object.to_rpc_data_or_self ) )
end

#load(dump) ⇒ Object



30
31
32
# File 'lib/cuboid/rpc/serializer.rb', line 30

def load( dump )
    serializer.load( decompress( dump ) )
end

#rpc_data(object) ⇒ Object

Simulates an object’s over-the-wire transmission by dumping and then loading.



41
42
43
# File 'lib/cuboid/rpc/serializer.rb', line 41

def rpc_data( object )
    load( dump( object ) )
end

#serializerObject



84
85
86
# File 'lib/cuboid/rpc/serializer.rb', line 84

def serializer
    MessagePack
end