[RUBY] Draw and understand Action Cable

Introduction

I had some time due to the corona turmoil, so I touched Rails' Action Cable.

I looked up the basic usage in the Rails guide, but it didn't come out very well, so I drew a diagram to understand it. In particular [Chapter on Terms](https://railsguides.jp/action_cable_overview.html#%E7%94%A8%E8%AA%9E%E3%81%AB%E3%81%A4%E3%81%84 Even after reading% E3% 81% A6), I didn't understand the relationship between each term, so I've organized it myself.

About terms

Connection, Consumer

ActionCable-Connection.png

WebSocket basics

Connection

Consumer

How to distinguish Consumer

Unlike HTTP, authentication information is not sent every time, so it is necessary to manage "who this connection belongs to" on the server side when establishing a connection.

Action Cable uses the Connection class ʻidentified_by` as a mechanism for this.

# app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
 
    def connect
      self.current_user = User.find_by(id: cookies.encrypted[:user_id])
    end
 
  end
end

Channel, Subscription

ActionCable-Subscription.png

Channel

Subscription

A new Subscription object is created with consumer.subscriptions.create and added to consumer.subscriptions as shown below.

chat_channel.js


import consumer from "./consumer"
consumer.subscriptions.create("ChatChannel", {
  //Abbreviation
});

Stream

ActionCable-Stream.png

Example

For example, if you define the following channel class, it will be linked to the stream chat_001 when you subscribe to ChatChannel.

chat_channel.rb


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

When the following code is executed in this state, the JSON string {" text ":" Hello, World! "} Is sent to the subscriber.

broadcast


data = {text: "Hello, World!"}
ActionCable.server.broadcast("chat_001", data)

The broadcast itself to the stream can be done from anywhere in your Rails application.

Multiple Streams

ActionCable-Stream-2.png

In the example in the previous section, it was a fixed string, so every subscription was tied to the same stream. However, since parameters can be passed to the server side when subscribing to a channel, it is possible to link to different streams for each user or each open page.

Summary

ActionCable-まとめ.png

I didn't really understand the relationship between streams and subscriptions, so I focused on that. In this figure, the stream seems to be indispensable, so I will organize it from the viewpoint of executing the server side method by the action parameter and write it in a separate article.

Recommended Posts

Draw and understand Action Cable
Real-time comment function with Action Cable (2/2)
Real-time comment function with Action Cable (1/2)