Implementing WebSockets With Ruby on Rails

Implementing WebSockets With Ruby on Rails

WebSockets are a powerful technology that allows for real-time, bidirectional communication between a client and a server. In a Ruby on Rails application, implementing WebSockets can enhance user experience by enabling features such as live notifications, chats, and updates without the need for constant page refreshes. This article will guide you through the process of implementing WebSockets in a Ruby on Rails application.

Prerequisites

Before you start implementing WebSockets, ensure you have the following:

  • Ruby on Rails installed (version 5.0 or above is recommended).
  • A basic understanding of Action Cable, which is the WebSocket framework in Rails.
  • A database set up (PostgreSQL is commonly used).

Setting Up Action Cable

Action Cable integrates WebSockets into Rails seamlessly. To get started, you need to set up your Rails application to use Action Cable.

rails new myapp --skip-javascript

This command creates a new Rails application without the default JavaScript files, allowing you to customize your setup for Action Cable.

Generate a Channel

Next, you can generate a new channel for your WebSocket communication. Channels handle the WebSocket connections for your application.

rails generate channel Chat

This command will create a new file under app/channels/chat_channel.rb. Open this file and implement your subscription logic:

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_channel"
  end
def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
def speak(data)
    ActionCable.server.broadcast("chat_channel", message: data['message'])
  end
end

Frontend Implementation

To send and receive messages, you need to set up JavaScript to interact with your channel. In your app/javascript/channels/chat_channel.js file, implement the following code:

import consumer from "./consumer"
consumer.subscriptions.create("ChatChannel", {
  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) {
    // Append the received message to the chat window
    const messages = document.getElementById("messages")
    messages.insertAdjacentHTML('beforeend', `

${data.message}

`) }, speak(message) { this.perform('speak', { message: message }) } })

Now, you can wire up your frontend form to send messages. In your application view, add a text input and a button:

<div id="chat">
  <div id="messages"></div>
  <input id="message" type="text" placeholder="Type your message...">
  <button id="send_message">Send</button>
</div>
<script>
  document.getElementById("send_message").addEventListener("click", function() {
    const messageInput = document.getElementById("message")
    App.cable.subscriptions.subscriptions[0].speak(messageInput.value)
    messageInput.value = ""
  })
</script>

Testing Your WebSockets

To test your WebSocket implementation, start your Rails server:

rails server

Once the server is running, open your application in multiple browser tabs, and send messages from one tab. You should see the messages appear in real-time in all open tabs without a page refresh.

Conclusion

Implementing WebSockets with Ruby on Rails using Action Cable can significantly enhance the interactivity of your web applications. With real-time features available, users can have a more engaging experience. Remember to handle security aspects such as authentication and authorization when dealing with WebSockets in production environments.

By following the steps above, you can easily set up a WebSocket-driven feature in your Rails application. Experiment with different functionalities, and leverage the power of real-time communication in your web projects!