This website uses cookies to enhance the user experience

Action Cable

Share:

Ruby on Rails Action Cable is a vital aspect of the Rails framework, enabling the easy use of WebSockets to establish full-duplex communication that facilitates live features like chat applications, notifications, real-time analytics, and numerous others.

This section will walk you through understanding Action Cable, its purpose, and how to use it via comprehensive text and code snippets.

Understanding Action Cable

Action Cable seamlessly integrates WebSockets with the rest of the Rails application. It enables real-time features to be written in Ruby in the same style and form as the rest of the application while still being performant and scalable. It's a full-stack offering that provides both a client-side JavaScript framework and a server-side Ruby framework.

The connection between the client and server is a persistent one. Thus, it allows messages to be passed back and forth without having to make multiple HTTP connection rounds.

Basic Components

Understanding the following three primary components will help you effectively use Action Cable:

  1. Connections
  2. Channels
  3. Subscriptions

Connections

Connections are instances of ActionCable::Connection::Base. When a client connects to the server, an object of this class is created. Connections are authenticated and identified.

Channels

Channels, defined as subclasses of ActionCable::Channel::Base, enable logical separation of concerns. Each channel encapsulates a logical unit of work, similar to how controllers work in regular Rails applications.

Subscriptions

Subscriptions are created when a consumer becomes interested in a channel. The client can subscribe to multiple channels.

Getting Started with Action Cable

To understand the usage of Action Cable entirely, let’s build a basic chat application.

Setting Up Action Cable

Action Cable is pre-installed in modern Rails applications. If it's not, it can be added to the Gemfile and installed via Bundle:

# Gemfile 
gem 'actioncable'

Generate a Channel

First, we generate a channel. Rails has built-in generators for channels. Our channel will be "Chat", and the method will be "speak".

rails generate channel Chat speak

This command creates several files including an empty app/channels/chat_channel.rb for our channel logic, and app/assets/javascripts/channels/chat.js for our JavaScript client-side logic.

Establish a Connection

The initial step is to modify our ApplicationCable::Connection to identify a connection. In this example, we'll use a hypothetical 'current_user' from a sign-in system.

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_user
    end

    private

    def find_user
      if verified_user = User.find_by(id: cookies.signed['user.id'])
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

Determine Channel

Next, it's time to configure our channel. Open our generated app/channels/chat_channel.rb:

class ChatChannel < ApplicationCable::Channel
  def subscribed
     stream_from "chat_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak(data)
    Message.create(content: data['message'])
  end
end

Client-side JavaScript

On the client side, subscription can be made to the Chat channel and the speak function can be engaged by writing the following JavaScript code in app/assets/javascripts/channels/chat.js:

App.chat = App.cable.subscriptions.create("ChatChannel", {
  connected: function() {
    // Called when the subscription is ready for use on the server
  },

  disconnected: function() {
    // Called when the subscription has been terminated by the server
  },

  received: function(data) {
    // Called when there's incoming data on the WebSocket for this channel
    console.log(data);
  },

  speak: function(message) {
    return this.perform('speak', { message: message });
  }
});

At the conclusion of these steps, we have a functioning, real-time chat channel. Users can send data to the server using App.chat.speak(), and the received chat messages can be handled within the received() function in the client-side JavaScript.

In conclusion, Action Cable is an efficient tool for building real-time applications using Ruby on Rails. It provides full-duplex communication, enabling a persistent connection between client and server, and integrates with Rails conventions, making it consistent and familiar to Rails developers. This has been a brief introduction, but there are many more possibilities when leveraging Action Cable in your applications.

0 Comment


Sign up or Log in to leave a comment


Recent job openings

Canada, Montreal, QC

Remote

Full-time

JavaScript

JavaScript

TypeScript

TypeScript

posted 2 days ago

Poland, Wrocław, Lower Silesian Voivodeship

Remote

SQL

SQL

Angular

Angular

+5

posted 2 days ago

United Kingdom, London, Belfast, Bristol, Gateshead, England

Remote

Full-time

posted 2 days ago

Spain, Madrid, Community of Madrid

Remote

Java

Java

TypeScript

TypeScript

+8

posted 2 days ago

Canada, Montreal, QC

Remote

Full-time

Java

Java

JavaScript

JavaScript

+16

posted 2 days ago