Module: Gapic::Protobuf

Defined in:
lib/gapic/protobuf.rb

Overview

A set of internal utilities for coercing data to protobuf messages.

Class Method Summary collapse

Class Method Details

.coerce(hash, to:) ⇒ Object

Creates an instance of a protobuf message from a hash that may include nested hashes. google/protobuf allows for the instantiation of protobuf messages using hashes but does not allow for nested hashes to instantiate nested submessages.

Parameters:

  • hash (Hash, Object)

    The hash to be converted into a proto message. If an instance of the proto message class is given, it is returned unchanged.

  • to (Class)

    The corresponding protobuf message class of the given hash.

Returns:

  • (Object)

    An instance of the given message class.

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gapic/protobuf.rb', line 32

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

.time_to_timestamp(time) ⇒ Google::Protobuf::Timestamp

Utility for converting a Ruby Time instance to a Google::Protobuf::Timestamp.

Parameters:

  • time (Time)

    The Time to be converted.

Returns:

  • (Google::Protobuf::Timestamp)

    The converted Google::Protobuf::Timestamp.



120
121
122
# File 'lib/gapic/protobuf.rb', line 120

def self.time_to_timestamp time
  Google::Protobuf::Timestamp.new seconds: time.to_i, nanos: time.nsec
end

.timestamp_to_time(timestamp) ⇒ Time

Utility for converting a Google::Protobuf::Timestamp instance to a Ruby time.

Parameters:

  • timestamp (Google::Protobuf::Timestamp)

    The timestamp to be converted.

Returns:

  • (Time)

    The converted Time.



110
111
112
# File 'lib/gapic/protobuf.rb', line 110

def self.timestamp_to_time timestamp
  Time.at timestamp.seconds, timestamp.nanos, :nanosecond
end