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.
Connection, Consumer
Connection
cookies
in connection.rb
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
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
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.
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.
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.