Class: Protobuf::Rpc::Services::Base

Inherits:
Protobuf::Rpc::Service
  • Object
show all
Defined in:
lib/protobuf/rpc/services/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_rpc(method, req = ::Protobuf::Rpc::Messages::RpcCompressedMessage, res = ::Protobuf::Rpc::Messages::RpcCompressedMessage) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/protobuf/rpc/services/base.rb', line 28

def self.define_rpc(method, req = ::Protobuf::Rpc::Messages::RpcCompressedMessage, res = ::Protobuf::Rpc::Messages::RpcCompressedMessage)
  self.rpc method, req, res

  define_method(method) do
    class_name = method.to_s.camelize.gsub('!', 'Bang').gsub('?', 'QuestionMark')
    result = nil
    req = Serializer.load(request)

    logger.debug(req.to_hash)

    begin
      interaction = Object.const_get("#{self.class.namespace}::Interactions::#{self.class.name.demodulize}::#{class_name}", false)
    rescue NameError => e
      result = Protobuf::Rpc::MethodNotFound.new(e.message)
      result.set_backtrace(e.backtrace)
    else
      begin
        result = interaction.run!(req.to_hash)
        case result
          when Protobuf::Message
            result
          when ::ActiveRecord::Base, ::ActiveRecord::Relation
            result = result.to_proto(deprecated: false, except: interaction.except_attributes, include: interaction.include_attributes)
          else
            result.respond_to?(:to_proto) ? result.to_proto : result
        end
      rescue => e
        result = e
      end
    end

    compress_with result
  end
end

.inherit_rpcs!Object



24
25
26
# File 'lib/protobuf/rpc/services/base.rb', line 24

def self.inherit_rpcs!
  superclass.rpcs.keys.each { |x| define_rpc(x) }
end

.inherited(subclass) ⇒ Object



16
17
18
# File 'lib/protobuf/rpc/services/base.rb', line 16

def self.inherited(subclass)
  subclass.inherit_rpcs!
end

.namespaceObject



20
21
22
# File 'lib/protobuf/rpc/services/base.rb', line 20

def self.namespace
  self.name.deconstantize.deconstantize
end

Instance Method Details

#compress_with(msg, serializer: :MSGPACK) ⇒ Object



9
10
11
12
13
14
# File 'lib/protobuf/rpc/services/base.rb', line 9

def compress_with(msg, serializer: :MSGPACK)
  if msg.is_a?(StandardError)
    msg = Messages::Error.new(error_class: msg.class.name, error_message: msg.message, error_backtrace: msg.backtrace)
  end
  respond_with Serializer.dump(msg, serializer: serializer)
end