-
Notifications
You must be signed in to change notification settings - Fork 17
Using the DataStore
The DataStore object is a private Hash. When you access it in a controller, you will be accessing a Hash that is private to the client that initiated the event currently executing. You can use it exactly as you would a regular Hash, except you do not have to worry about it being overridden by the next client that triggers an event. This means that unlike instance variables in WebsocketRails controllers which are shared amongst all connected clients, the data store is an easy place to temporarily persist data for each user between events.
You can access the DataStore object by using the data_store controller method.
class ChatController < WebsocketRails::BaseController
def new_user
# The instance variable would be overwritten when the next user joins
@user = User.new(name: message[:user_name]) # No Good!
# This will be private for each user
data_store[:user] = User.new(name: message[:user_name]) # Good!
broadcast_user_list
end
end
If you wish to output an Array of the assigned values in the data store for every connected client, you can use the each_<key>
method, replacing <key>
with the hash key that you wish to collect.
Given our ongoing chat server example, we could collect all of the current User objects like so: d
data_store[:user] = 'User3'
data_store.each_user
=> ['User1','User2','User3']
A simple method for broadcasting the current user list to all clients would look like this:
def broadcast_user_list
users = data_store.each_user
broadcast_message :user_list, users
end