PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

ruby

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support
  • Reconnection Policies

Configuration API for PubNub Ruby SDK

Ruby V4 complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Initialization

Installing

In order to use pubnub ruby gem you need to install it. You can do it via rubygems command:

gem install pubnub

Or add it to your Gemfile.

gem 'pubnub', '~> 5.0.0'

Usage

To use pubnub you need to require it in your files.

require 'pubnub'

That's it, you can use PubNub ruby client right away.

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publish_key and subscribe_key.

Method(s)

To Initialize PubNub you can use the following method(s) in the Ruby V4 SDK:

Pubnub(subscribe_key, publish_key, secret_key, auth_key, cipher_key, ssl, uuid, heartbeat, callback, ttl, open_timeout, read_timeout, idle_timeout, s_open_timeout, s_read_timeout, s_idle_timeout, logger, origin, http_sync)
ParameterTypeRequiredDefaultsDescription
subscribe_keyString, SymbolYesYour subscribe key.
publish_keyString, SymbolOptionalYour publish key, required to publish messages.
secret_keyString, SymbolOptionalYour secret key, required for PAM.
auth_keyString, SymbolOptionalYour auth key.
cipher_keyStringOptionalYour cipher key, it's used to encrypt and decrypt messagages if set.
sslBooleanOptionalfalseIf set to true ssl connection will be used.
uuidStringYesUUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
heartbeatIntegerOptionalSetting value of heartbeat enables heartbeat with given value. Heartbeat starts with first async subscribe. Disabled by default.
callbackLambdaOptionalThat callback will be automatically passed to all method calls fired from this client (like publish, history, subscribe). Will be overwritten by the callback passed to called event.
ttlIntegerOptionalDefault ttl for grant and revoke.
open_timeoutIntegerOptional10Timeout for opening connection for non-subscribe events.The value is in seconds.
read_timeoutIntegerOptional10Timeout for reading for non-subscribe events.The value is in seconds.
idle_timeoutIntegerOptional10Timeout for idle for non-subscribe events.The value is in seconds.
s_open_timeoutIntegerOptional310Timeout for opening connection for subscribe.The value is in seconds.
s_read_timeoutIntegerOptional310Timeout for read for subscribe.The value is in seconds.
s_idle_timeoutIntegerOptional310Timeout for idle for subscribe.The value is in seconds.
loggerObjectOptionalLogger instance that outputs logs to 'pubnub.log'Custom logger instance.
originStringOptionalps.pndsn.comCustom origin.
Add method that allows changing the origin.#origin=(origin)
http_syncBooleanOptionalfalseMethod 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.
random_ivBooleanOptionaltrueWhen true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (< 4.6.0) with existing applications. Never disable random IV on new applications.

Basic Usage

Initialize the PubNub client API:

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

pubnub = Pubnub.new(
    subscribe_key: :demo,
    publish_key:   :demo,
    ssl: true,
    uuid: 'myUniqueUUID'
)

Returns

It returns the PubNub instance for invoking PubNub APIs like publish(), subscribe(), history(), here_now(), etc.

Other Examples

  1. Initialize the client:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    pubnub = Pubnub.new(
        publish_key: 'demo',
        subscribe_key: 'demo',
        uuid: 'myUniqueUUID'
    )
    
  2. Initialization for a Read-Only client:

    In the case where a client will only read messages and never publish to a channel, you can simply omit the publish_key when initializing the client:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    # Initialize for Read Only Client
    pubnub = Pubnub.new(
        subscribe_key : 'demo'
    )
    
  3. Use a custom UUID

    Set a custom UUID to identify your users.

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    # initialize
    pubnub = Pubnub.new(
        publish_key: 'myPublishKey',
        subscribe_key: 'mySubscribeKey',
        uuid: 'myUniqueUUID'
    )
    
  4. Initializing with SSL Enabled:

    This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    pubnub = Pubnub.new(
        subscribe_key: :demo,
        publish_key:   :demo,
        ssl: true,
        uuid: 'myUniqueUUID'
    )
    
  5. Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
    https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

    Note

    Anyone with the secret_key can grant and revoke permissions to your app. Never let your secret key be discovered, and to only exchange it / deliver it securely. Only use the secret_key on secure server-side platforms.

    When you init with secret_key, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

    For applications that will administer PAM permissions, the API is initialized with the secret_key as in the following example:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    pubnub = Pubnub.new(subscribe_key: 'my_subkey', secret_key: 'my_secretkey', uuid: 'myUniqueUUID')
    

    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secret_key to sign all PAM messages to the PubNub Network.

Event Listeners

Description

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

Listeners should be added before calling the method.

Adding Listeners

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
    signal: ->(_envelope) {}, # Handle signal message
    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)

Removing Listeners

pubnub.remove_listener(name: 'my_listener')
# or
pubnub.remove_listener(callbacks)

Listeners Example

# 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)

Presence to a Channel Group

Description

This functions subscribes to the presence channel of a channel group.

Method(s)

To do Presence to a Channel Group you can use the following method(s) in Ruby V4 SDK:

Go to Subscribe Method

Basic Usage

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')

Authentication Key

Description

This function provides the capability to get a user's auth_key.

Method(s)

auth_key

This method doesn't take any arguments.

Basic Usage

pubnub.auth_key

Returns

The current authentication key.

← Getting StartedPublish & Subscribe →
  • Initialization
    • Installing
    • Usage
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • Event Listeners
    • Description
  • Presence to a Channel Group
    • Description
    • Method(s)
    • Basic Usage
  • Authentication Key
    • Description
    • Method(s)
    • Basic Usage
    • Returns
© PubNub Inc. - Privacy Policy