Class: Google::Cloud::Pubsub::Message

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

Overview

Message

Represents a Pub/Sub Message.

Message objects are created by Topic#publish. Subscription#pull returns an array of ReceivedMessage objects, each of which contains a Message object. Each ReceivedMessage object can be acknowledged and/or delayed.

Examples:

require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

# Publish a message
topic = pubsub.topic "my-topic"
message = topic.publish "task completed"
message.data #=> "task completed"

# Pull a message
sub = pubsub.subscription "my-topic-sub"
received_message = sub.pull.first
received_message.message.data #=> "task completed"

Instance Method Summary collapse

Constructor Details

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

Create an empty Message object. This can be used to publish several messages in bulk.



55
56
57
58
59
60
61
62
# File 'lib/google/cloud/pubsub/message.rb', line 55

def initialize data = nil, attributes = {}
  # Convert attributes to strings to match the protobuf definition
  attributes = Hash[attributes.map { |k, v| [String(k), String(v)] }]

  @grpc = Google::Pubsub::V1::PubsubMessage.new(
    data: String(data).encode("ASCII-8BIT"),
    attributes: attributes)
end

Instance Method Details

#attributesObject

Optional attributes for the message.



73
74
75
76
77
# File 'lib/google/cloud/pubsub/message.rb', line 73

def attributes
  return @grpc.attributes.to_h if @grpc.attributes.respond_to? :to_h
  # Enumerable doesn't have to_h on Ruby 2.0, so fallback to this
  Hash[@grpc.attributes.to_a]
end

#dataObject

The message payload. This data is a list of bytes encoded as ASCII-8BIT.



67
68
69
# File 'lib/google/cloud/pubsub/message.rb', line 67

def data
  @grpc.data
end

#message_idObject Also known as: msg_id

The ID of this message, assigned by the server at publication time. Guaranteed to be unique within the topic.



82
83
84
# File 'lib/google/cloud/pubsub/message.rb', line 82

def message_id
  @grpc.message_id
end

#published_atObject Also known as: publish_time

The time at which the message was published.



89
90
91
# File 'lib/google/cloud/pubsub/message.rb', line 89

def published_at
  Convert.timestamp_to_time @grpc.publish_time
end