Class: Gcloud::Pubsub::Topic::Batch

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

Overview

Batch object used to publish multiple messages at once.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Batch.



28
29
30
31
32
33
34
# File 'lib/gcloud/pubsub/topic/batch.rb', line 28

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

Instance Attribute Details

#messagesObject (readonly)



24
25
26
# File 'lib/gcloud/pubsub/topic/batch.rb', line 24

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



40
41
42
43
44
# File 'lib/gcloud/pubsub/topic/batch.rb', line 40

def publish data, attributes = {}
  # 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



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/gcloud/pubsub/topic/batch.rb', line 48

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: String(arr[0]).encode("ASCII-8BIT"),
                        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