2016-06-07 62 views
0

我的代碼非常依賴用戶是否在線。用ActionCable保持用戶「在線」

目前我設置ActionCable這樣的:

class DriverRequestsChannel < ApplicationCable::Channel 
    def subscribed 
     stream_from "requests_#{current_user.id}" 
    end 

    def unsubscribed 
    current_user.unavailable! if current_user.available? 
    end 
end 

現在我會非常喜歡的覆蓋是用戶的,而不是剛進入脫機只是關閉瀏覽器的情況。但是,取消訂閱的問題在於它進行頁面刷新。所以每次刷新頁面時都會觸發unsubscribed。因此即使他們認爲他們可用,他們也會被視爲不可用。

現在關鍵是可用不是默認的,所以我可以放回去,這是用戶選擇接收請求的東西。

有沒有人有處理這種情況的最佳方法的經驗?

回答

0

你不應該只依靠的WebSockets,還放了用戶的在線狀態到數據庫:

1:添加遷移

class AddOnlineToUsers < ActiveRecord::Migration[5.0] 
    def change 
    add_column :users, :online, :boolean, default: false 
    end 
end 

2:添加AppearanceChannel

class AppearanceChannel < ApplicationCable::Channel 
    def subscribed 

    stream_from "appearance_channel" 

    if current_user 

     ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :on } 

     current_user.online = true 

     current_user.save! 

    end 


    end 

    def unsubscribed 

    if current_user 

     # Any cleanup needed when channel is unsubscribed 
     ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :off } 

     current_user.online = false 

     current_user.save!  

    end 


    end 

end 

現在,您可以保證免受任何偶然的Websockets連接損失。在每個HTML頁面刷新做2件事:

  1. 檢查數據庫的用戶在線狀態。
  2. 連接到套接字並訂閱外觀頻道。

這樣的組合方式可以隨時爲您提供用戶的在線狀態。