Search code examples
ruby-on-railsreal-timeserver-sent-eventsobservers

How to push content in real time in rails 3


I'm wondering the way to push content in my site in real time.. I've researched some time and I realized that there are many ways to do this work.

Some considerations first: I have a Rails 3 App with some social functionality..one of the features I want to achieve is to notify my users when a new activity is created. My first approach was to implement SSE and a controller that searches in the DB for new registries after the last loaded activity.

This can work but this requires too many DB queries when all I need is to push the activity to all active users (related with that activity) when a new activity is created, without the need to do DB queries..

My second approach was to create a route pointing to a controller and an observer to catch when an new activity is created, later pass the current activity created to the controller and finally render the activity partial through SSE.

Here comes my problem.. how can connect the observer with the controller and pass it the current activity to be rendered? And there, can I use another controller type such as a Metal Controller or even an Abstract one?

In this point I realized that could be another approach to do this job.. It'd be really nice if I could find a way to do this without having to develop it in another language or framework.. I think that should have a gem that could do real time apps easier.. What do you think?? I'm on the right way or what I should do to achieve this?? Many Thanks!!


Solution

  • Rails 3.0+ Push Content in Real-time with PubNub

    In order to safely and securely push real-time updates to your users with some social functionality on your web site or web app there are, as you say, many options available and many nuances to consider with this as well. There is a gem for this! And I will help you get started by providing a simple start guide here for your Rails 3.0+ app and web site. First you'll want to run gem install pubnub which is the real-time component known as PubNub that will allow you to send notifications directly to targeted users or a group of users on your website and apps. This allows you to target only those who are online and interested in receiving the notifications from your Rails server. You can consider this as efficient server-sent events that require no DB Lookup or other resource intensive operations on your servers.

    Ruby GEM Install

    gem install pubnub
    

    Require PubNub GEM

    require 'pubnub'
    

    Initialize The PubNub Class

    pubnub = Pubnub.new(
        :publish_key   => 'demo', # publish_key only required if publishing.
        :subscribe_key => 'demo', # required always
        :secret_key    => nil,    # optional - message signing
        :cipher_key    => nil,    # optional - AES 256 Crypto
        :ssl           => true    # optional - SSL 2048bit
    )
    

    From Rails 3.0+ Send Messages to the Web App

    Now from your Rails App with the pubnub class ready, you can send any kind of JSON data type including a String, Number, Array and Dictionary/Object:

    • a "String"
    • a Number 123
    • an array [ 1, 2, 3 ]
    • an object { :a => "apple" }

    The following code will show you the process which will pass a message from your Rails App directly to the browser or web app that you users are running. Essentially sending the data to your users when you need to directly from your server. The pubnub.publish(...) function will serialize the message you send as a JSON for transport to your mobile and web apps.

    ## Broadcast or Unicast to Browser App User(s)
    pubnub.publish(
        :channel  => "event_feed_channel",
        :message  => { :event => "update", :from => "Jay", :feed => "New Updates!" },
        :callback => lambda { |info| puts info }
    )
    

    This process works great for performance and security considerations and never requires DB queries; saving you from hammering on your Database server and other resource intensive operations. You may consider this process as SSE (Server-Sent Events) while you are using the PubNub GEM in your Rails applications.

    Using the PubNub GEM you are essentially sending events from your Server direct to your User's Browser/App. It removes the need for client-side periodic AJAX requests. This is because you are only sending data to your user's when new information is available. You may also consider using more PubNub Real-time Network features like Presence and Storage/Playback by visiting the home site to learn more details about the Ruby features. And also use the Developers Dev Console for debugging if needed during your integration into your Rails code.

    Setup Browser to Receive Server-Sent Events

    Next you need to setup your app to receive the Server-Sent Events by running init and passing in the

    <script src=http://cdn.pubnub.com/pubnub-3.4.2.min.js ></script>
    <script>(function(){
    
        // Class Setup
        var pubnub = PUBNUB.init({ subscribe_key : 'demo' });
    
        // Event Hook Setup
        pubnub.subscribe({
            channel : "event_feed_channel",
            message : function(m){ pubnub.events.fire( m.event, m ) }
        });
    
        // RECEIVE the "update" Server Broadcast Event in the Browser
        pubnub.events.bind( "update", function(message) {
            console.log( "update a <div> with received event: ", m );
        } );
    
    })();</script>
    

    Note you may be interested in Advanced Subscribe Connectivity Options and Events.

    Notice how the "update" event is identical to the :event => "update" message value in the ruby code. This means that the event will be triggered based on the name you supply and you need to bind the event to trigger code to execute on your Web App page. Inside this triggered event you will update the User Interface with any relevant details that the user would want to see on their screen in real-time.

    Also notice the :channel => "event_feed_channel" is the publish channel, and this must be identical as the subscribe channel in the JavaScript client code.

    If you want to read the source code of the Ruby GEM, it is available via GitHub PubNub Ruby-based APIs.

    These are the basics for getting started with Ruby 3.0+ Apps and sending events directly from your server to your End-users. Note this also works for Mobile Apps that run on iOS Web Browsers or Android Browsers. Also old versions of IE are supported for this mechanism. In addition you could optionally consider server sent events from your Rails servers directly to Native iOS applications and Native Android Applications. If you have any questions ask them here on this Forum.