ライブチャットとActionCable

ライブチャットの例を使用して、最近、ActionCableをRuby on Railsプロジェクトに統合する方法に関する短いメモを公開したいと思います。 ActionCableの仕組みについては詳しく説明しませんが、使用例を簡単に紹介します。

準備する


まず、Gemfileにactioncableとpumaを追加します

gem 'actioncable', github: 'rails/actioncable' gem 'puma' 

ActionCableは、メインアプリケーションプロセスとは別に起動されます。 したがって、 PumaマルチスレッドWebサーバーを使用します。

建築家チャット


メインページで、ユーザーはニックネームを入力します。その後、Cookieにニックネームを書き込み、チャットページで編集します。

config / routes.rbにいくつかのルートを追加します

 resources :messages, only: [:index, :create] resources :sessions, only: [:new, :create] 

アクションコントローラーを作成します。 クッキーのニックネーム:

 # app/controllers/sessions_controller.rb class SessionsController < ApplicationController def create cookies.signed[:username] = params[:session][:username] redirect_to messages_path end end 

ユーザー認証フォームアプリ/ビュー/セッション/ new.html.slim:

 = form_for :session, url: sessions_path do |f| p = f.label :username, '  ' p = f.text_field :username p = f.submit '' 

チャット自体では、印刷されたメッセージへの応答として200を送信します。

 # app/controllers/messages_controller.rb class MessagesController < ApplicationController def create head :ok end end 

ビューアプリ/ビュー/メッセージ/index.html.slim:

 p = cookies.signed[:username] p #messages p = form_for :message, url: messages_path, remote: true, id: 'messages-form' do |f| p = f.label :body, ' :' p = f.text_field :body p = f.submit '' 

メッセージはAJAXによってサーバーに送信されます。

ActionCalbeを構成する


ActionCableとの統合を担当する3つのクラスを作成しましょう。

 # app/channels/application_cable/connection.rb module ApplicationCable class Connection < ActionCable::Connection::Base end end # app/channels/application_cable/channel.rb module ApplicationCable class Channel < ActionCable::Channel::Base end end # app/channels/messages_channel.rb class MessagesChannel < ApplicationCable::Channel def subscribed stream_from 'messages' end end 

作成したディレクトリをautoload_pathsに追加することを忘れないでください。 これで、 MessagesChannelチャネルにサブスクライブしている全員が、 サブスクライブされたメソッドで定義された対応するストリームでメッセージを受信できるようになります。 - メッセージ

ActionCableはRedisを介したメッセージングを提供します。 すでにインストールされていると仮定します。 config / redis / cable.ymlでそれとの通信を設定する必要があります:

 development: &dev :url: redis://localhost:6379 :host: localhost :port: 6379 :timeout: 1 :inline: true test: *dev production: *dev 

Pumaを構成します。

 # cable/config.ru require ::File.expand_path('../../config/environment', __FILE__) Rails.application.eager_load! require 'action_cable/process/logging' run ActionCable.server 

ポート34523でプーマを起動します。

 # /bin/bash bundle exec puma -p 34523 cable/config.ru 

これで、クーガーは./bin/cableコマンドによって起動されます。

一般的なチャットにメッセージを送信する



app / controllers / messages_controller.rbを少し調整しましょう:
 class MessagesController < ApplicationController def create ActionCable.server.broadcast 'messages', message: params[:message][:body], username: cookies.signed[:username] head :ok end end 


最も重要なことは、チャンネル登録です。 2つのコーヒーファイルを作成してみましょう(忘れずに再取得してください):

 #app/assets/javascripts/channels/messages.coffee App.messages = App.cable.subscriptions.create 'MessagesChannel', received: (data) -> $('#messages').append("<p><b>[#{data.username}]:</b> #{data.message}</p>") #app/assets/javascripts/channels/index.coffee #= require cable #= require_self #= require_tree . @App = {} App.cable = Cable.createConsumer('ws://127.0.0.1:34523') 

以上です。
いつものように、小さなプロジェクト-https://github.com/lon10/live-chat

Source: https://habr.com/ru/post/J264589/


All Articles