Class: Protobuf::Rpc::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/protobuf/rpc/serializer.rb

Class Method Summary collapse

Class Method Details

.dump(msg, serializer:) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/protobuf/rpc/serializer.rb', line 4

def self.dump(msg, serializer:)
  return msg if msg.is_a?(::Protobuf::Rpc::Messages::RpcCompressedMessage)
  dumped_message = ::Protobuf::Rpc::Messages::RpcCompressedMessage.new(compressed: false)

  # serialize the message
  case msg
    when ::Protobuf::Message
      proto(dumped_message, msg)
    when StandardError
      error = ::Protobuf::Rpc::Messages::Error.new(error_class: msg.class.name,
                                  error_message: msg.message,
                                  error_backtrace: msg.backtrace)
      proto(dumped_message, error)
    else
      case serializer.to_s.upcase.to_sym
        when :MSGPACK
          msgpack(dumped_message, msg)
        when :OJ
          oj(dumped_message, msg)
        when :MULTI_JSON
          multi_json(dumped_message, msg)
        when :JSON
          json(dumped_message, msg)
        when :YAML
          yaml(dumped_message, msg)
        when :MARSHAL
          marshal(dumped_message, msg)
        else
          raw(dumped_message, msg)
      end
  end

  # if size is greater than 16k, compress it
  if dumped_message.response_body.size > 16384
    dumped_message.compressed = true if msg.is_a?(String)
    dumped_message.response_body = ActiveSupport::Gzip.compress(dumped_message.response_body) if dumped_message.compressed
  else
    dumped_message.compressed = false
  end

  dumped_message
end

.load(msg) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/protobuf/rpc/serializer.rb', line 47

def self.load(msg)
  return msg unless msg.is_a?(::Protobuf::Rpc::Messages::RpcCompressedMessage)
  body = msg.compressed ? ActiveSupport::Gzip.decompress(msg.response_body) : msg.response_body

  if msg.response_type.present?
    Object.const_get(msg.response_type).decode(body)
  else
    case msg.serializer.name
      when :RAW
        body
      when :MSGPACK
        require 'msgpack'
        MessagePack.unpack(body)
      when :MARSHAL
        Marshal.load(body)
      when :JSON
        begin
          require 'multi_json'
          MultiJson.load(body)
        rescue LoadError
          require 'json'
          JSON.parse(body)
        end
      when :YAML
        require 'yaml'
        YAML.load(body)
      else
        body
    end
  end
end