, . ActionCable Rails 5 API ( gem 'devise_token_auth), :
():
{"command":"subscribe","identifier":"{\"channel\":\"UnreadChannel\"}"}
():
{"command":"message","identifier":"{\"channel\":\"UnreadChannel\",\"correspondent\":\"client2@example.com\"}","data":"{\"action\":\"process_unread_on_server\"}"}
- ActionCable , - :
/var/lib/gems/2.3.0/gems/actioncable-5.0.1/lib/action_cable/connection/subscriptions.rb:74
def find(data)
if subscription = subscriptions[data['identifier']]
subscription
else
raise "Unable to find subscription with identifier: #{data['identifier']}"
end
end
: , . correspondent, - .
, , correspondent :
():
{"command":"message","identifier":"{\"channel\":\"UnreadChannel\"}","data":"{\"correspondent\":\"client2@example.com\",\"action\":\"process_unread_on_server\"}"}
, .
UnreadChannel:
class UnreadChannel < ApplicationCable::Channel
def subscribed
if current_user
unread_chanel_token = signed_token current_user.email
stream_from "unread_#{unread_chanel_token}_channel"
else
reject
end
end
def unsubscribed
end
def process_unread_on_server param_message
correspondent = param_message["correspondent"]
correspondent_user = User.find_by email: correspondent
if correspondent_user
unread_chanel_token = signed_token correspondent
ActionCable.server.broadcast "unread_#{unread_chanel_token}_channel",
sender_id: current_user.id
end
end
end
helper: ( - , Rails cookie )
def signed_token string1
token = string1
secret_key_base = Rails.application.secrets.secret_key_base
verifier = ActiveSupport::MessageVerifier.new secret_key_base
signed_token1 = verifier.generate token
pos = signed_token1.index('--') + 2
signed_token1.slice pos..-1
end
, SUBSCRIBE, MESSAGE. ( "" ). , subscribed (!) - ( SUBSCRIBE) ( - hook subscribed).
, subscribed hook :
stream_from "unread_#{unread_chanel_token}_channel"
, , unread_chanel_token - "" .
, (, \"channel\":\"UnreadChannel\") "" (, "" ) - ( , ), "", .
- "" - , :
ActionCable.server.broadcast "unread_#{unread_chanel_token}_channel", sender_id: current_user.id
, ?
. ?