Last modified: Mon Aug 28 2017 22:54:29 GMT+0800 (Malay Peninsula Standard Time)

Chapter 2. ActionCable

Rails 5 has one of the most highly anticipated features: Websocket support via Action Cable. With the new feature, we are able to build a real-time chat or messaging Web Application. There are a lot of tutorial online on teaching you how to create a messaging Web Application. There is no point for me to repeat again.

In this chapter, I will use Action Cable to refresh the page when a new data is committed to the database. The use case of my example would be a dashboard to receive real time order update.

2.1 Initial Setup

To generate MVC components, use the scaffold command. Assuming that we are generating a page for order and the order contains a field name item, we would use the command below.

rails generate scaffold Order item:string

Then, migrate the database by using the command below.

rake db:migrate

Figure 2.1.1 shows the index page of Order with one field, named item.

Figure 2.1.1: Index of Order

2.2 Configure Model, Channel, and Job

Now, we have to use the commonly used rails command to generate Action Cable channels. Since we are generating a channel for our order, I will name my channel Order.

rails generate channel Order

Figure 2.2.1 shows three files are generated after the command above is executed.


Figure 2.2.1: Three files are created

Figure 2.2.2 shows there are two default methods in order_channel.rb created by the ActionCable subscribed and unsubscribed. A user will be automatically subscribed to the particular channel when the specific page is visited.

Figure 2.2.2: Default method created by the channel

Add the code in Table 2.2.1 to allow streaming to all users. This method is global and not user specific. This means that all the users that have the page open will receive the broadcast.

Table 2.2.1: Code to add to channel

#MyApp/app/channels/order_channel.rb

#add in subscribed method  
stream_from “order_channel”

Then, add the code in Table 2.2.2 to the route. This is part of the ActionCable configuration.

Table 2.2.2: Code to add to routes

#MyApp/app/config/routes.rb

mount ActionCable.server, at: '/cable'

Now, we have to add the action where each commit to the database will trigger the broadcast action. This includes create, update, and delete actions.

Table 2.2.3: Code to add to Model

#MyApp/app/model/order.rb

#Code to remove
class Order < ApplicationRecord  
end

#Code to add
class Order < ApplicationRecord  
  after_create_commit { OrderBroadcastJob.perform_later self }  
  after_update_commit { OrderBroadcastJob.perform_later self }  
  after_destroy { OrderBroadcastJob.perform_later self }  
end

We have almost everything set up. Now, we have to create a broadcast job for our Order. Follow the instruction in Table 2.2.4 and Table 2.2.5 and add the code to the file. Whenever a job is triggered, it will go to the perform method and then render method to render the page. Whenever a data is received, the index page will be reloaded.

Table 2.2.4: File to create and code to add to Job

#MyApp/app/jobs/order_broadcast_job.rb

class OrderBroadcastJob < ApplicationJob  
  queue_as :default  

  def perform(order)  
    ActionCable.server.broadcast 'order_channel', item: render(order)  
  end  

  private   
    def render(order)  
        ApplicationController.renderer.render(partial: 'orders/order', locals: {order: order})  
    end  
end

Table 2.2.5: Code to add to Channel

#MyApp/app/assets/javascripts/channels/order.coffee

#Add mentioned code
App.order = App.cable.subscriptions.create "OrderChannel",  
  connected: ->  
    # Called when the subscription is ready for use on the server  

  disconnected: ->  
    # Called when the subscription has been terminated by the server  

  received: (data) ->  
    # Called when there's incoming data on the websocket for this channel  
    location.reload(); <<<<< Add this line

2.3 Testing and Verification

We have successfully set up everything that we need to do. Fire up your Rails server to do some testing. Visit our Order index page and your Rails server output log will show something similar to Figure 2.3.1. The highlighted box shows the Web Application is listening and waiting for request.


Figure 2.3.1: Rails server log

Open two browsers side by side to perform testing. In the first browser window, stay at the index page. Create a new Order by using your second browser window. When a new item is created successfully, the first browser will reload automatically. Figure 2.3.2 shows the result when a new Order was created.


Figure 2.3.2: Result of both browser windows when an order is created

Figure 2.3.3 shows the result when an order is edited. We can see that the first browser window is reloaded by itself and shows the updated information.


Figure 2.3.3: Result of both browser windows when an order is edited

Figure 2.3.4 shows the result when an order is deleted. We can see that the first browser window is reloaded by itself and removed from the list.


Figure 2.3.4: Result of both browser windows when an order is deleted

Whenever a user leave the specific webpage that you have ActionCable feature, the server will show the log. Figure 2.3.5 shows the result where two users leave the page. The highlighted box shows the time where each user leave the page.


Figure 2.3.5: Server log when two users leave the page

2.4 Deploy Feature To Heroku

The feature that we have tested in Chapter 2.3 will only work locally. In order for the application to work correctly when we deploy it to Heroku PaaS, we have to add a Gem to our Gemfile. Follow the instuction in Table 2.4.1 to add the Gem.

Table 2.4.1: Code to add to Gemfile

#MyApp/gemfile

gem 'redis', '~> 3.0'

In your Heroku dashboard, go to your application and search “Redis To Go” in the Add-ons section. Figure 2.4.1 shows the operation where Redis To Go is being added to my application.


Figure 2.4.1: Provision Redis To Go

After provisioning, the add on will show up in the Add-ons list. Figure 2.4.2 shows Redis To Go is added to my Add-ons.


Figure 2.4.2: Redis To Go added to Add-ons list

Select “Redis To Go” and you will be redirected to a configuration page. Figure 2.4.3 shows a Redis link shown in the General section.


Figure 2.4.3: Link of Redis is shown in General section

In the configuration page, copy the link in the General section and replace it based on the section stated in Table 2.4.2. Do note that your link begins with redis://…….

Table 2.4.2: Code to add to cable.yml

#MyApp/config/cable.yml

#replace YOUR_LINK_HERE with your Redis link
production:  
  adapter: redis  
  url: YOUR_LINK_HERE

Commit your changes and your Web Application in Heroku will be able to work as expected after it is built successfully.

results matching ""

    No results matching ""