# frozen_string_literal: true require "google/protobuf" # This module provides classes for the Makit gem. module Makit module Proto3Formats JSON = 0, PRETTY_JSON = 1, BINARY = 3 end # This class provide methods for serializing and deserializing objects. # class Serializer attr_accessor :format_map def initialize(proto3_format = Proto3Formats::PRETTY_JSON) @format_maps = { ::Google::Protobuf::MessageExts => proto3_format, } end # Serialize an object to a byte[] or a string def serialize(object) raise "Object is nil" if object.nil? raise "object is not of type ::Google::Protobuf::MessageExts" if !object.is_a? ::Google::Protobuf::MessageExts case @format_maps[::Google::Protobuf::MessageExts] when Proto3Formats::JSON puts "Serializing to protobuf json format" object.to_json when Proto3Formats::PRETTY_JSON puts "Serializing to protobuf pretty json format" json = object.to_json pretty_json = JSON.pretty_generate(JSON.parse(json)) pretty_json when Proto3Formats::BINARY puts "Serializing to protobuf binary format" serialized_object = object.to_proto else raise "Unknown serialization format" end end # Deserialize a byte[] or a string to an object def deserialize(type, data) raise "data is nil" if data.nil? case @format_maps[::Google::Protobuf::MessageExts] when Proto3Formats::JSON raise "data is not of type string" if !data.is_a? String json = data puts "Deserializing from protobuf json format into type #{type}" # use the from_json method to deserialize the object type.decode_json(json) when Proto3Formats::PRETTY_JSON raise "data is not of type string" if !data.is_a? String json = data puts "Deserializing from protobuf pretty json format into type #{type}" # use the from_json method to deserialize the object type.decode_json(json) when Proto3Formats::BINARY #raise "data is not of type byte[]" if !data.is_a? Array bytes = data puts "Deserializing from protobuf binary format into type #{type}" type.decode(bytes) else raise "Unknown serialization format" end end end # class Storage end # module Makit