Sha256: 52d0b072088c9bece8ce24bc5b10b9e2ec07ad00b6047b9790dff65f741b81b0

Contents?: true

Size: 1.62 KB

Versions: 8

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module HermesMessengerOfTheGods
  module Concerns
    module GrpcProtobuf
      extend ActiveSupport::Concern

      included do
        class_attribute :_protobuf_class

        alias_method :_pre_grpc_protobuff_init, :initialize
        def initialize(protobuf, options = {})
          raise "#{self.class} requires a Protobuf for initialization" unless protobuf.is_a?(self.class._protobuf_class)

          _pre_grpc_protobuff_init(protobuf.to_h.merge!(options))
        end

        def _build_for_transmission
          # Hermes expects a hash
          JSON.parse(serialize_with_defaults)
        end

        def serialize_with_defaults
          # Use the protobuf class' encode_json to generate defaults for any missing keys
          self.class._protobuf_class.encode_json(message_as_proto, emit_defaults: true)
        end

        def message_as_proto
          # Build a proto with the incoming hash
          self.class._protobuf_class.new(to_message)
        end
      end

      class_methods do
        def build(message)
          new(protobuf_class.new(message))
        end

        def from_message(attrs = {}, &blk)
          # Hermes provides a hash, but we want to leverage the protobuf's built in deserialization, so dump it to json
          pb = _protobuf_class.decode_json(JSON.dump(attrs))
          new(pb, &blk)
        end

        def protobuf_class
          _protobuf_class
        end

        def protobuf_class=(klass)
          self._protobuf_class = klass
          klass.descriptor.each do |f|
            attr_accessor f.name.to_sym
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
hermes_messenger_of_the_gods-3.0.0 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-3.0.0.rc5 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-3.0.0.rc4 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-3.0.0.rc3 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-3.0.0.rc2 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-3.0.0.rc1 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-2.4.2 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb
hermes_messenger_of_the_gods-2.4.1 lib/hermes_messenger_of_the_gods/concerns/grpc_protobuf.rb