2017-08-18 30 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

您可以在頻道爲此下

def unsubscribed 
    # Any cleanup needed when channel is unsubscribed 
    end 

/application_cable/your_channel.rb

此外,ActionCable does work with sessions,它需要一點調整,雖然的。

如果你嚴重有關測試ActionCable的併發性(即有關於在一個高檔的生產中使用ActionCable嚴重的想法),我會有種勸你已經放棄了和插件anyCable。會爲你節省很多時間。

相關問題