ruby - Rails ActionCable unsubscribe users when browser close -
i'm testing actioncable simple example. want see how many users connected @ time on website. users not registered in system. users assigned session variable uuid. make example simple possible have not included model or database.
#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
views simple
#app/views/users/index.html.erb <h1>users</h1> <div id="users"> <%= render "user",user: @user %> </div>
partial users:
#app/views/users/_user.html.erb <div class="user"> user : <%= user %> </div>
i use job call socket
#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
and channel
app.user = app.cable.subscriptions.create "userchannel", connected: -> disconnected: -> received: (data) -> console.log(data) $("#users").prepend(data.message)
this works correctly. in each browser open uuid connected visible. not use database persistence, first open browser has uuid , rest of browsers goes n-1 uuid visible. it's not important.
my question is:
if browser closes, how can send message delete uuid template?
actioncable not work sessions.
ruby version: 2.4.0 rails version: 5.1.3 jquery installed via yarn
thanks!!!!
you can under
def unsubscribed # cleanup needed when channel unsubscribed end
in channels/application_cable/your_channel.rb
besides, actioncable does work sessions, takes bit of tweaking though.
if you're serious testing concurrency of actioncable (i.e have serious thoughts using actioncable in upscale production), kind of advise give , plugin anycable. save ton of time.
Comments
Post a Comment