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
45
46
47
48
49
50
51
# File 'lib/gcloud/pubsub/topic/batch.rb', line 40

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/gcloud/pubsub/topic/batch.rb', line 55

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