RubyRuby V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


 

These docs are for PubNub 4.0 for Ruby which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for Ruby.

If you have questions about the PubNub for Ruby SDK, please contact us at support@pubnub.com.

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publish_key at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special Ruby V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Ruby V4 SDK:
  1. ParameterTypeRequiredDescription
    channelStringYesSpecify the channel name to publish the messages.
    messageObjectYesSerializable object that has defined #to_json method.
    storeBooleanOptionalSpecifies if message should be stored for history.

    Default true.

    compressedBooleanOptionalSpecifies if message should be compressed.

    Default false.

    publish_keyStringOptionalSpecifies the required publish_key to use to send messages to a channel.
    http_syncBooleanOptional

    Default false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).

    For sync methods Envelope object will be returned.

    callbackLambda accepting one parameterOptional

    Callback that will be called for each envelope.

    For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Publish a message to a channel:

pubnub.publish(
	channel: 'my_channel',
	message: { text: 'Hi!' }
) do |envelope|
	puts envelope.status
end
 
Before running the above publish example, either using the Debug Console, or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
The function returns the following formatted response:
[1, "Sent", "13769558699541401"]
  1. pubnub.publish(
    	message:  {
    		key: {
    			inner_key: :value
    		}
    	},
    	channel:   :whatever
    )
  2. pubnub.publish(message: 'Not gonna store that', store: false)
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Ruby V4 SDK:
  1. ParameterTypeRequiredDescription
    channelStringYesSpecify the channel name to publish the messages.
    messageObjectYesSerializable object that has defined #to_json method.
    compressedBooleanOptionalSpecifies if message should be compressed.

    Default false.

    publish_keyStringOptionalSpecifies the required publish_key to use to send messages to a channel.
    http_syncBooleanOptional

    Default false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).

    For sync methods Envelope object will be returned.

    callbackLambda accepting one parameterOptional

    Callback that will be called for each envelope.

    For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Fire a message to a channel:

pubnub.fire(
    channel: 'my_channel',
    message: { 
        text: 'Hi!'
    }
) do |envelope|
    puts envelope.status
end
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribe_key at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.
 
You can be notified of connectivity via the envelope.status. By waiting for the envelope.status to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.
Using Ruby V4 SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the Ruby V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsString, Symbol, ArrayOptionalSpecify the channels to subscribe to. It is possible to specify multiple channels as an array. It is possible to subscribe to wildcard channels. See Examples for more info.
    channel_groupsString, Symbol, ArrayOptionalSpecifies the group to subscribe to. It is possible to specify multiple groups as an array. See Examples for more info.
    presenceString, Symbol, ArrayOptionalSpecifies the channel to presence subscribe to. It is possible to specify multiple channels as an array. See Examples for more info.
    presence_callbackLambda accepting one argumentOptionalCallback that is called for each presence event from wildcard subscribe. Works only with http_sync set to true.
    with_presenceBooleanOptionalSubscribes to all presence channels of channels listed in channels parameter.
    http_syncBooleanOptional

    Default false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).

    For sync methods they will return array of Envelopes - envelope object for each message.

    callbackLambda accepting one parameterOptional

    Callback that is called for each retrieved message. Works only with http_sync set to true.

    The response of the subscription is handled by Listener. Please see the Listeners section for more details.
Subscribe to a channel:
# Subscribe to channel 'my_channel'.
pubnub.subscribe(
	channels: :my_channel
)
The output below demonstrates the response format to a successful call:
[[], "Time Token"]
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    # Subscribe to channels (with presence) and groups
    pubnub.subscribe(
    	channels: ['debug', 'info', 'warn'],
    	channel_groups: ['ruby_group', 'jruby_group', 'rbx_group'],
    	presence: ['debug', 'info', 'warn']
    )
    # You will be subscribed to channels: debug, info, warn, debug-pnpres, info-pnpres and warn-pnpres
    # and to groups: ruby_group, jruby_group, rbx_group.
  2. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    # Subscribes to room0, room0-pnpres, room1, room1-pnpres, room2, room2-pnpres
    pubnub.subscribe(
        channels: ['room0', 'room1', 'room2'], 
        with_presence: true
    )
    {
    	"action": "join",
    	"timestamp": 1345546797,
    	"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    	"occupancy": 2
    }
    
    {
        "action" : "leave",
        "timestamp" : 1345549797,
        "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "occupancy" : 1
    }
    {
    	"action": "timeout",
    	"timestamp": 1345549797,
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"occupancy": 0
    }
    
    {
    	"action": "state-change",
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"timestamp": 1345549797,
    	"data": {
    		"isTyping": true
    	}
    }
    
    {
    	"action":"interval",
    	"timestamp":1474396578,
    	"occupancy":2
    }
    

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "joined" : ["uuid2", "uuid3"],
        "timedout" : ["uuid1"]
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "here_now_refresh" : true
    }
    
  3. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    # Subscribe to wildcard channel 'ruby.*' (make sure you have wildcard subscribe enabled in your pubnub admin console!)
    # specify two different callbacks for messages from channels and presence events in channels.
    pubnub.subscribe(
    	channels: 'ruby.*'
    )
  4. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    require 'pubnub'
    
    PUBKEY = 'demo'
    SUBKEY = 'demo'
    
    
    pubnub = Pubnub.new(
        subscribe_key: SUBKEY, 
        publish_key: PUBKEY,
        ssl: true
    )
    
    callback = Pubnub::SubscribeCallback.new(
        message: ->(envelope) { 
            puts "MESSAGE: #{envelope.result[:data]}"
        },
        presence: ->(envelope) {
            puts "PRESENCE: #{envelope.result[:data]}"
        }
    )
    
    pubnub.add_listener(callback: callback)
    subs = pubnub.subscribe(channels: 'public', with_presence: true)
    
    subs.add_observer do
        pubnub.set_state(channels: 'public', state: {key: 'val'}) do |env|
            if env.error?
                # handle error
            else
                # success
            end
        end
    end
  5. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    # Subscribe to group
    pubnub.subscribe(
    	channel_groups: 'ruby_group'
    )
  6. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub = Pubnub.new(
        subscribe_key: :demo, 
        publish_key: :demo
    )
    
    callback = Pubnub::SubscribeCallback.new(
        message:  ->(_envelope) {
        },
        presence: ->(envelope) { 
            puts "PRESENCE: #{envelope.result[:data]}" 
        },
        status:   ->(_envelope) { 
        }
    )
    
    pubnub.add_listener(callback: callback)
    
    pubnub.presence(channel_groups: 'family')
  7.  
    The loop will exit when there is no subscribed channel left, closing the program in turn.
    require 'pubnub'
    pubnub = Pubnub.new(
        subscribe_key: :demo,
        publish_key: :demo
    )
    
    pubnub.subscribe(channels: :whatever)
    while pubnub.subscribed_channels.size > 0 do
        sleep 1
    end
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the Ruby V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsSymbol, StringOptionalSpecify the channels to unsubscribe from. (Required if channel_groups is not specified)
    channel_groupsSymbol, StringOptionalSpecify the channel_groups to unsubscribe from. (Required if channels is not specified)
    http_syncBooleanOptional

    Default false. Method will be executed asynchronously and will return future, to get it's value you can use value method. If set to true, method will return array of envelopes (even if there's only one envelope).

    For sync methods Envelope object will be returned.

    callbackLambda accepting one parameterOptional

    Callback that will be called for each envelope.

    For async methods future will be returned, to retrieve value Envelope object you have to call value method (thread will be locked until the value is returned).

Unsubscribe from a channel:
pubnub.unsubscribe(
	channel: 'my_channel'
) do |envelope|
	puts envelope.status
end
#<Pubnub::Envelope
    @status = {
        :code => 200,
        :operation => :leave,
        :category => :ack,
        :error => false,
        # [...]
    },
    # [...]
>
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe(
    	channel: ['chan1','chan2','chan3']
    ) do |envelope|
    	puts envelope.status
    end
    pubnub.unsubscribe(
        channel: ['chan1','chan2','chan3']
    ) do |envelope|
        puts envelope.result[:data][:messages]
    end
    {
    	"action" : "leave"
    }
    
  2. pubnub.leave(channel_group: "cg1") do |envelope|
    	puts envelope.status
    end
  3. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.leave(group: ["cg1", "cg2"]) do |envelope|
    	puts envelope
    end

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

callback = Pubnub::SubscribeCallback.new(
	message:  ->(_envelope) {}, # this will be fired only for non-presence messages
	presence: ->(_envelope) {}, # this will be fired only for presence messages
	status:   ->(envelope)  do  # this will be fired for status messages and errors
	if envelope.status[:error]
		case envelope.status[:category]
			when Pubnub::Constants::STATUS_ACCESS_DENIED # :access_denied
				# Access denied. Double check PAM etc.
			when Pubnub::Constants::STATUS_TIMEOUT # :timeout
				# Timeout error
			when Pubnub::Constants::STATUS_NON_JSON_RESPONSE # :non_json_response
				# Non json response
			when Pubnub::Constants::STATUS_API_KEY_ERROR # :api_key_error
				# API key error
			when Pubnub::Constants::STATUS_ERROR
				# Other error
			else
				# Shouldn't happen
			end
		end
	end
)

pubnub.add_listener(name: 'my_listener', callback: callback)
pubnub.remove_listener(name: 'my_listener')
# or
pubnub.remove_listener(callbacks)
# Init pubnub client
pubnub_client = Pubnub.new(subscribe_key: 'demo', publish_key: 'demo')

# First callbacks object
callbacks0 = Pubnub::SubscribeCallback.new(
  message:  ->(envelope) { puts "C0 MESSAGE: #{envelope.result[:data][:message]}" },
  presence: ->(envelope) { puts "C0 PRESENCE: #{envelope.result[:data][:message]}" },
  status:   ->(envelope) { puts "C0 STATUS: #{envelope.result[:data][:message]}" }
)

# Second callbacks object
callbacks1 = Pubnub::SubscribeCallback.new(
  message:  ->(envelope) { puts "C1 MESSAGE: #{envelope.result[:data][:message]}" },
  presence: ->(envelope) { puts "C1 PRESENCE: #{envelope.result[:data][:message]}" },
  status:   ->(envelope) { puts "C1 STATUS: #{envelope.result[:data][:message]}" }
)

# Adding listener allows you to specify name, it's not required to specify a name
pubnub_client.add_listener(name: 'c0', callback: callbacks0)

# Let's subscribe somewhere
pubnub_client.subscribe(channel: :demo, presence: :demo)

# SOME OUTPUT:
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683357, "uuid"=>"fc0c0460-44b4-4338-b7e9-1b534b85072e", "occupancy"=>2}
# C0 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683374, "uuid"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>3}
# C0 MESSAGE: {"text"=>"hey"}

# Adding another subscriber
pubnub_client.add_listener(name: 'c1', callback: callbacks1)

# SOME OUTPUT WITH TWO LISTENERS ACTIVE:
# C0 MESSAGE: {"text"=>"hey"}
# C1 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"leave", "timestamp"=>1461683435, "uuid"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}
# C1 PRESENCE: {"action"=>"leave", "timestamp"=>1461683435, "uuid"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}

# We're removing subscriber by giving it's name
pubnub_client.remove_listener(name: 'c1')

# SOME OUTPUT AFTER REMOVING C1 LISTENER
# C0 MESSAGE: {"text"=>"hey"}
# C0 MESSAGE: {"text"=>"hey"}
# C0 PRESENCE: {"action"=>"join", "timestamp"=>1461683698, "uuid"=>"3efb92f6-bf02-4373-aafa-996527718ecc", "occupancy"=>2}

# We're removing subsciber by giving it's object, now we don't have any listeners active
pubnub_client.remove_listener(callback: callbacks0)
This functions subscribes to the presence channel of a channel group.
To do Presence to a Channel Group you can use the following method(s) in Ruby V4 SDK
  1. Go to Subscribe Method
Subscribe to the presence channel of a channel group
pubnub = Pubnub.new(
    subscribe_key: :demo, 
    publish_key: :demo
)

callback = Pubnub::SubscribeCallback.new(
    message:  ->(_envelope) {
    },
    presence: ->(envelope) { 
        puts "PRESENCE: #{envelope.result[:data]}" 
    },
    status:   ->(_envelope) { 
    }
)

pubnub.add_listener(callback: callback)

pubnub.presence(channel_groups: 'family')

Go to Presence