Rails ActionCable在浏览器关闭时取消订阅用户

时间:2017-08-18 09:38:33

标签: ruby-on-rails ruby actioncable

我正在用一个非常简单的例子测试ActionCable。 我想看一下网站上有多少用户连接。 用户未在系统中注册。 为用户分配了一个带有uuid的会话变量。 为了使示例尽可能简单,我没有包含模型或数据库。

#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通过纱线安装

感谢!!!!

2 个答案:

答案 0 :(得分:1)

这对你很有帮助

class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    stream_from "appearance"
    @current_user = User.find(params[:room])
    @current_user.appear
    ActionCable.server.broadcast('appearance',{data: @current_user.appear,action: 'SubscribedList'})
  end

  def unsubscribed
    if @current_user.present? 
      ActionCable.server.broadcast('appearance',{data: @current_user.disappear,action: 'SubscribedList'})
    end
  end

end

你可以将param传递给订阅但是不可能取消订阅的params。因此,当您调用subscribe时,将current_user存储到一个变量,并在取消订阅时将其告诉我。

答案 1 :(得分:0)

您可以在

下执行此操作
  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

在您的频道/ application_cable / your_channel.rb

此外,ActionCable does work with sessions虽然需要一些调整。

如果你认真关于测试ActionCable的并发性(即认真考虑在高级制作中使用ActionCable),我会建议你放弃已经和插件{{3 }}。将为您节省大量时间。