Sha256: ed4ec1fbcbe6d520783a85592f1eab7c93e00c2e2570174753d92f1414bfe162
Contents?: true
Size: 1.65 KB
Versions: 10
Compression:
Stored size: 1.65 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 = {}) unless protobuf.is_a?(self.class._protobuf_class) raise "#{self.class} requires a Protobuf for initialization" end _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
10 entries across 10 versions & 1 rubygems