Class: Google::Cloud::Pubsub::Topic::Publisher

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/pubsub/topic/publisher.rb

Overview

Topic Publisher object used to publish multiple messages at once.

Examples:

require "google/cloud"

gcloud = Google::Cloud.new
pubsub = gcloud.pubsub

topic = pubsub.topic "my-topic"
msgs = topic.publish do |t|
  t.publish "new-message-1", foo: :bar
  t.publish "new-message-2", foo: :baz
  t.publish "new-message-3", foo: :bif
end

Instance Method Summary collapse

Instance Method Details

#publish(data, attributes = {}) ⇒ Object

Add multiple messages to the topic. All messages added will be published at once. See Google::Cloud::Pubsub::Topic#publish



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/google/cloud/pubsub/topic/publisher.rb', line 54

def publish data, attributes = {}
  # Convert IO-ish objects to strings
  if data.respond_to?(:read) && data.respond_to?(:rewind)
    data.rewind
    data = data.read
  end
  # Convert data to encoded byte array to match the protobuf defn
  data = String(data).force_encoding("ASCII-8BIT")
  # Convert attributes to strings to match the protobuf definition
  attributes = Hash[attributes.map { |k, v| [String(k), String(v)] }]
  @messages << [data, attributes]
end