Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - Action Cable - list of connected users

I'm starting with Rails 5 and Action Cable and I would like to display a list of names of all connected registered users (something like facebook's green circle).

I managed to get the name of the user, but now I'm thinking what's the best way to store them. In node I would simply in an array on server, but as I know that is not possible in ActionCable.

What is the most effective way to do this? Storing them in database (postgres, redis)?

like image 226
dedekm Avatar asked Apr 16 '16 10:04

dedekm


3 Answers

Effectiveness completely depends on your needs. Do you need the persistence of a database?

Otherwise feel free to just use an in-memory array on your Rails server as well. Perhaps memcache, or something similar.

This is a very open-ended answer because it's a very open-ended question. I think you should give some consideration to your needs :)

like image 86
ekampp Avatar answered Oct 31 '22 22:10

ekampp


Add an online field to Users

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

Make an appearance channel

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

Make sure all your visitors subscribe to the AppearanceChannel when they enter your site (via some JavaScript call, see http://guides.rubyonrails.org/action_cable_overview.html#client-side-components ). Add the authorisation to Action Cable:

Like this https://rubytutorial.io/actioncable-devise-authentication/

or like that How To use devise_token_auth with ActionCable for authenticating user?

Apply again some JavaScript code to detect the incoming "{ user: current_user.id, online: :on }" message and set the green dot on a user avatar.

like image 29
prograils Avatar answered Oct 31 '22 21:10

prograils


I believe the best way would be to store them in redis, because it's really fast. However, more important is the fact that if you use postgres or any other RDBMS, you'll create unnecessary load on your db

like image 20
Nikita Misharin Avatar answered Oct 31 '22 22:10

Nikita Misharin