DEV Community

Cover image for Using Action Cable for Real-Time Applications in Ruby on Rails
Jospin Ndagano
Jospin Ndagano

Posted on

Using Action Cable for Real-Time Applications in Ruby on Rails

Action Cable is a powerful feature in Ruby on Rails that allows developers to create real-time applications. It integrates WebSockets seamlessly into Rails, enabling bi-directional communication between the server and clients. This article will guide you through the basics of Action Cable and how to implement it in your Rails applications.

What is Action Cable?

Action Cable provides a framework for implementing WebSockets in Rails applications. WebSockets allow for persistent connections, enabling real-time features like chat applications, live notifications, and updates without requiring the client to refresh the page.

Setting Up Action Cable

To get started with Action Cable in your Rails application, follow these steps:

  1. Create a New Rails Application If you don't have a Rails application set up yet, create one:
rails new my_realtime_app
Enter fullscreen mode Exit fullscreen mode
cd my_realtime_app
Enter fullscreen mode Exit fullscreen mode
  1. Generate a Channel

Channels are the core components of Action Cable. They handle the WebSocket connections and define how data is sent and received.
Generate a new channel using the Rails generator:

rails generate channel Chat
Enter fullscreen mode Exit fullscreen mode

This command creates several files, including:
app/channels/chat_channel.rb: The channel logic.
app/javascript/channels/chat_channel.js: The client-side JavaScript for the channel.

  1. Implement the Channel Logic

Open app/channels/chat_channel.rb and define the behavior of the channel:

# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_channel" # Stream from this channel
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def receive(data)
    ActionCable.server.broadcast("chat_channel", message: data['message'])
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Set Up the Client-Side Code

Next, open app/javascript/channels/chat_channel.js and set up the client-side subscription:

// app/javascript/channels/chat_channel.js
import consumer from "./consumer";

const chatChannel = consumer.subscriptions.create("ChatChannel", {
  connected() {
    console.log("Connected to the chat channel!");
  },

  disconnected() {
    console.log("Disconnected from the chat channel.");
  },

  received(data) {
    // Handle incoming messages
    const messageElement = document.createElement("div");
    messageElement.innerText = data.message;
    document.getElementById("messages").appendChild(messageElement);
  },

  sendMessage(message) {
    this.perform("receive", { message: message });
  }
});

export default chatChannel;
Enter fullscreen mode Exit fullscreen mode
  1. Create a View for Chat

Now, create a simple view to display and send messages. Open app/views/chat/index.html.erb and add the following code:

<h1>Chat Room</h1>
<div id="messages"></div>
<input type="text" id="message_input" placeholder="Type your message here..." />
<button id="send_message">Send</button>

<script>
  document.addEventListener("DOMContentLoaded", () => {
    const sendMessageButton = document.getElementById("send_message");
    const messageInput = document.getElementById("message_input");

    sendMessageButton.addEventListener("click", () => {
      const message = messageInput.value;
      chatChannel.sendMessage(message);
      messageInput.value = ""; // Clear input field
    });
  });
</script>
Enter fullscreen mode Exit fullscreen mode
  1. Set Up the Routes

Add a route for the chat page in config/routes.rb:

Rails.application.routes.draw do
  root "chat#index"
end
Enter fullscreen mode Exit fullscreen mode
  1. Start the Rails Server

Run your Rails server:

rails server
Enter fullscreen mode Exit fullscreen mode
  1. Test the Application

Open your browser and navigate to http://localhost:3000. Open multiple tabs or windows to simulate different users in the chat. When you send a message from one window, it should appear in real-time in the other windows.

Action Cable makes it easy to add real-time features to your Ruby on Rails applications. By leveraging WebSockets, you can create interactive applications that respond instantly to user actions. Whether you're building a chat application, live notifications, or collaborative tools, Action Cable provides the tools you need to enhance user experience with real-time capabilities. Start exploring Action Cable in your projects to unlock the full potential of real-time web applications.

Top comments (0)