Question

I was wondering how to implement user presence with PubNub in Rails apps, but I didn't find a complete guide to how to implement this feature in both server and client side.

Was it helpful?

Solution

PubNub Presence with Ruby and JavaScript

Get started easily with PubNub Presence in Ruby and JavaScript by following this short guide which connects the state between the two PubNub SDKs. First you'll want to make sure you have the latest PubNub Ruby GEM client SDK install on your server. But before we get into the coding aspect we can talk about what PubNub Presence actually is.

PubNub Presence Introduction

PubNub Presence allows you to ask the question "Who is there?" and receive back an answer in the form of a List of UserIDs and an occupancy count of who is currently online right now.

Usually you ask this question in the context of a PubNub Channel. User's connect to a PubNub Channel in order to receive a stream of data from the PubNub Network. You control the stream by way of Channels by publishing and subscribing to channels by any valid UTF-8 string. Sometimes you want to know the current state of the PubNub Channel by requesting the current activity and list of connected users on the channel. You can do this by using PubNub Presence feature which provides the answer you seek.

PubNub Presence SDKs

Let's get starte by listing the two starting steps of including/loading the GEM ans JavaScript SDKs for your target platforms (This time it's Ruby+JavaScript Combo).

Install PubNub Ruby GEM

sudo gem install pubnub

Next you will ensure that you are running one of the latest JavaScript SDKs on your JavaScript Client App (usually a mobile phone app or website app).

Include PubNub JavaScript Client SDK

<script src=http://cdn.pubnub.com/pubnub-3.4.2.min.js ></script>

Now that you have accessed the two necessary base SDK libs for Ruby and JavaScript, you are able to receive/transmit information freely over the PubNub Network. Next we'll talk about how you can easily receive presence events as they occur on your PubNub Channel and also how you can query directly for the current channel state with here_now() API.

PubNub Dev Console - Presence

Use the PubNub Developer's Console to Monitor Presence Events.

You can use the PubNub Developer's Console to watch Presence Events as they occur. You will be able to see the event payload in JSON form in the presence section which is shown in the following image:

There are three events "action"s you can receive including:

  • "join" - A new user joined the channel.
  • "leave" - A user left the channel.
  • "timeout" - A user dropped connection and timed out.

PubNub Presence with REST

PubNub Here Now

With PubNub Presence you have access to TWO REST routes. The easiest route is the here_now() route.

PubNub Presence with SDKs

Example Source Code in JavaScript

The following is an example of method in JavaScript to receive data on a Channel and also receive Presence Events for that channel as they occur in real-time. Also you will notice the paramaters that are passed to you in your Function Callback. This method allows you to receive a stream of data into your JavaScript Application. Note there is a second method to receive presence data (called here_now()) which we will cover a bit further down.

<script>(function(){
    var pubnub = PUBNUB.init({
        subscribe_key : 'demo'
    });

    pubnub.subscribe({
        channel    : "hello_world",                        // YOUR CHANNEL.
        message    : function( message, env, channel ) {}, // RECEIVE MESSAGE.
        presence   : function( message, env, channel ) {   // PRESENCE EVENTS.
            console.log( "Channel: ",            channel           );
            console.log( "Join/Leave/Timeout: ", message.action    );
            console.log( "Occupancy: ",          message.occupancy );
            console.log( "User ID: ",            message.uuid      );
        }

    })
})();</script>

Example Source Code in Ruby

Here is Ruby Code which is the ruby method to receive Presence Events in real-time as they occur. You can process the stream or (Firehose) of events as they come in. Note there is a second method to receive presence data (called here_now()) which we will cover a bit further down.

require 'pubnub'

pubnub = Pubnub.new(
    :publish_key   => 'demo', # publish_key only required if publishing.
    :subscribe_key => 'demo', # required
    :secret_key    => nil,    # optional, if used, message signing is enabled
    :cipher_key    => nil,    # optional, if used, encryption is enabled
    :ssl           => nil     # true or default is false
)

## Receive Presence Events on a Channel
pubnub.presence(
    :channel  => :hello_world,
    :callback => lambda { |event_data| puts(event_data) }
)

When an event occurs (such as a user joining) the output data will look like:

{"action":"join", "timestamp":1364261400, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":4}

on a User Disconnect, the presence event is triggered as:

{"action":"leave", "timestamp":1364251540, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":3}

and potentially in the event of an error/timeout:

{"action":"timeout", "timestamp":1364251540, "uuid":"9d497a30-3af2-4b67-a6b3-82f254711c11", "occupancy":3}

Here_Now in JavaScript

There is a here_now() function available to you that allows you to issue a single REST request to the PubNub Network that gets the Current state of a channel's connectivity. The request looks like:

<script>(function(){
    var pubnub = PUBNUB.init({
        subscribe_key : 'demo'
    });

    pubnub.here_now({
        channel  : 'hello_world',
        callback : function (message) { console.log(message) }
    });
})();</script>

and the response object will look like:

{"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}

Here_Now in Ruby

Just like in JavaScript the same function for here_now() is available in Ruby too. Here is the ruby syntax version:

require 'pubnub'

pubnub = Pubnub.new(
    :publish_key   => 'demo', # publish_key only required if publishing.
    :subscribe_key => 'demo', # required
    :secret_key    => nil,    # optional, if used, message signing is enabled
    :cipher_key    => nil,    # optional, if used, encryption is enabled
    :ssl           => nil     # true or default is false
)

pubnub.here_now(
    :channel  => :hello_world,
    :callback => lambda { |event_data| puts(event_data) }
)

And the response object data is identical to what is available to you in JavaScript.

{"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}

Finally if you want to use the simple JSON REST interface provided by the PubNub Network, you can issue the following requests easily:

curl http://pubsub.pubnub.com/v2/presence/sub_key/demo/channel/hello_world

and the response output is identical:

{"uuids":["754e58b3-a79b-4d91-8f6c-5d994e43a310","175c2c67-b2a9-470d-8f4b-1db94f90e39e","fafd273d-9be5-4049-a6ce-653c467f7c5d"],"occupancy":3}

That's it! Super simple and easy to use PubNub Network Presence with Ruby on Rails and JavaScript. If you have any questions please contact PubNub directly and also visit the following links for more details:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top