Background: I'm working on an app that has a JS frontend, and a Rails backend. I've been able to successfully create a vanilla JS websocket client, that properly connects to and receives broadcasts from a Rails Actioncable-enabled websocket server.
The Problem and TLDR: I'm trying to get the total count of clients that connected and passed in specific data upon connecting.
Details: For example, say I have something like this:
//Client waves to server, says where they are from by passing in country to say_hi method on backend
const wave = {
command: 'message',
identifier: JSON.stringify({
channel: 'CountryChannel',
}),
data: JSON.stringify({
action: 'say_hi',
country: "USA",
}),
};
socket.send(JSON.stringify(wave));
Respectively, on the backend I have a say_hi
method that is able to get my passed in country value.
class CountryChannel< ApplicationCable::Channel
def subscribed
stream_from 'country'
end
def say_hi(data)
@country = data['country'] #@country = "USA"
end
end
So I now want to be able to somehow see the amount of waves from "USA".
I'm a complete beginner in Rails, and have been going down the ActionCable docs rabbit-hole. I tried searching SO for anything like this online and found:
ActionCable - how to display number of connected users? My problem with this is the approved answer (along with its caveats) would show the count of "all" the connection on that stream, whereas I want to segment that based on the data.
On the same link, I also saw an answer where you could use the
:identified_by
param in Connection object. My issue with that is I just can't figure out anywhere how to set that from my client. Again, I'm a noob at all this so it's probably straightfoward, but I've just been unable to connect the dots.I know that I could approach this by creating specific streams based on a parameter and have something like:
stream_from "country#{@country}" # streams country@USA
But I'm lost as to see the amount of clients that are currently receiving broadcasts on this stream, or something like that. Specifically, I just don't know what to use from ActionCable to be able to do this.
Any ideas? I'd love to further specify or provide any more info if needed. Just feel free to ask. Thanks!