2017-08-18 9 views
0

私は非常に簡単な例でActionCableをテストしています。 ウェブサイトで一度に何人のユーザーが接続されているのかを見たいと思っています。 ユーザーはシステムに登録されていません。 ユーザーには、uuidを使用してセッション変数が割り当てられます。 例をできるだけシンプルにするために、モデルやデータベースは含めていません。Rails ActionCableは、ブラウザが閉じるときにユーザを退会させます。

#app/controller/users_controller.rb 

class UsersController < ApplicationController 

    def index 
    if session[:user].nil? 
     session[:user] = SecureRandom.uuid 
    end 
    @user = session[:user] 
    UserBroadcastJob.perform_later @user 
    end 
    end 

ビューは

ユーザーのための部分的な
#app/views/users/index.html.erb 

<h1>Users</h1> 

<div id="users"> 
    <%= render "user",user: @user %> 
</div> 

非常に単純です:

#app/views/users/_user.html.erb 

<div class="user"> 
    User : <%= user %> 
</div> 

私はソケット

#app/jobs/user_broadcast_job.rb 

class UserBroadcastJob < ApplicationJob 
queue_as :default 

    def perform(user) 
    ActionCable.server.broadcast 'user_channel', message: render_user(user) 
    end 

    def render_user(user) 
    ApplicationController.renderer.render(partial: 'users/user', locals: { user: user }) 
    end 
end 

とチャネル

を呼び出すためのジョブを使用し
App.user = App.cable.subscriptions.create "UserChannel", 
connected: -> 

disconnected: -> 

received: (data) -> 
console.log(data) 
$("#users").prepend(data.message) 

これは正しく動作します。各ブラウザで私は開いているuuidが表示されている開いている。 私は永続性のためにデータベースを使用しないので、最初に開いているブラウザはすべてuuidを持ち、残りのブラウザはn-1 uuidになります。大事なことじゃない。

私の質問は:

ブラウザが閉じた場合、どのように私はテンプレートからUUIDを削除するメッセージを送ることができますか?

ActionCableはセッションでは機能しません。

Rubyのバージョン:2.4.0 Railsのバージョン:糸を介してインストール5.1.3 jqueryの

感謝!!!!

答えて

0

あなたは他に

your_channel.rb/application_cableあなたのチャンネル/中

def unsubscribed 
    # Any cleanup needed when channel is unsubscribed 
    end 

の下にこれを行うことができ、ActionCable does work with sessionsは、それはしかし微調整には多少時間がかかります。

あなたがActionCableの同時実行のテストに関する深刻なら(すなわちは高級な生産にActionCableの使用についての深刻な思考を持っている)、私は一種のすでにあきらめてanyCableをプラグインすることができ助言します。時間を節約できます。

関連する問題