module Gapic::Protobuf
def self.coerce hash, to:
-
(Object)
- An instance of the given message class.
Parameters:
-
to
(Class
) -- The corresponding protobuf message class of the given hash. -
hash
(Hash, Object
) -- The hash to be converted into a proto message. If an instance of the proto message
def self.coerce hash, to: return hash if hash.is_a? to return nil if hash.nil? # Special case handling of certain types return time_to_timestamp hash if to == Google::Protobuf::Timestamp && hash.is_a?(Time) # Sanity check: input must be a Hash raise ArgumentError, "Value #{hash} must be a Hash or a #{to.name}" unless hash.is_a? Hash hash = coerce_submessages hash, to.descriptor to.new hash end
def self.coerce_submessage val, field_descriptor
-
field_descriptor
(Google::Protobuf::FieldDescriptor
) -- The field descriptor. -
val
(Object
) -- The value to coerce
Other tags:
- Private: -
def self.coerce_submessage val, field_descriptor if val.is_a? Array # Assume this is a repeated message field, iterate over it and coerce # each to the message class. # Protobuf will raise an error if this assumption is incorrect. val.map do |elem| coerce elem, to: field_descriptor.subtype.msgclass end elsif field_descriptor.label == :repeated # Non-array passed to a repeated field: assume this is a map, and that # a hash is being passed, and let protobuf handle the conversion. # Protobuf will raise an error if this assumption is incorrect. val else # Assume this is a normal single message, and coerce to the message # class. coerce val, to: field_descriptor.subtype.msgclass end end
def self.coerce_submessages hash, message_descriptor
-
(Hash)
- A hash whose nested hashes have been coerced.
Parameters:
-
message_descriptor
(Google::Protobuf::Descriptor
) -- The protobuf descriptor for the message. -
hash
(Hash
) -- The hash whose nested hashes will be coerced.
Other tags:
- Private: -
def self.coerce_submessages hash, message_descriptor return nil if hash.nil? coerced = {} hash.each do |key, val| field_descriptor = message_descriptor.lookup key.to_s coerced[key] = if field_descriptor&.type == :message coerce_submessage val, field_descriptor elsif field_descriptor&.type == :bytes && (val.is_a?(IO) || val.is_a?(StringIO)) val.binmode.read else # For non-message fields, just pass the scalar value through. # Note: if field_descriptor is not found, we just pass the value # through and let protobuf raise an error. val end end coerced end
def self.time_to_timestamp time
-
(Google::Protobuf::Timestamp)
- The converted Google::Protobuf::Timestamp.
Parameters:
-
time
(Time
) -- The Time to be converted.
def self.time_to_timestamp time Google::Protobuf::Timestamp.new seconds: time.to_i, nanos: time.nsec end
def self.timestamp_to_time timestamp
-
(Time)
- The converted Time.
Parameters:
-
timestamp
(Google::Protobuf::Timestamp
) -- The timestamp to be converted.
def self.timestamp_to_time timestamp Time.at timestamp.seconds, timestamp.nanos, :nanosecond end