Class: Gcloud::Pubsub::Topic::Publisher

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

Overview

Topic Publisher object used to publish multiple messages at once.

Examples:

require "gcloud"

gcloud = Gcloud.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 Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = nil, attributes = {}) ⇒ Publisher

Returns a new instance of Publisher.



41
42
43
44
45
46
47
# File 'lib/gcloud/pubsub/topic/publisher.rb', line 41

def initialize data = nil, attributes = {}
  @messages = []
  @mode = :batch
  return if data.nil?
  @mode = :single
  publish data, attributes
end

Instance Attribute Details

#messagesObject (readonly)



37
38
39
# File 'lib/gcloud/pubsub/topic/publisher.rb', line 37

def messages
  @messages
end

Instance Method Details

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

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



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

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 definition
  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

#to_gcloud_messages(message_ids) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/gcloud/pubsub/topic/publisher.rb', line 68

def to_gcloud_messages message_ids
  msgs = @messages.zip(Array(message_ids)).map do |arr, id|
    Message.from_grpc(
      Google::Pubsub::V1::PubsubMessage.new(
        data: arr[0], attributes: arr[1], message_id: id))
  end
  # Return just one Message if a single publish,
  # otherwise return the array of Messages.
  if @mode == :single && msgs.count <= 1
    msgs.first
  else
    msgs
  end
end