ruby 49 lines · 9 steps

How a typing indicator works in Rails ActionCable

An ActionCable channel tracks who's typing using short-lived cache keys and periodic sweeps to broadcast live presence.

Explained by highlit
1class ChatChannel < ApplicationCable::Channel
2 periodically :sweep_stale_typists, every: 3.seconds
3 
4 def subscribed
5 @room = Room.find(params[:room_id])
6 stream_for @room
7 end
8 
9 def unsubscribed
10 return unless @room
11 
12 Rails.cache.delete(typing_key)
13 broadcast_typists
14 end
15 
16 def start_typing
17 Rails.cache.write(typing_key, current_user.name, expires_in: 5.seconds)
18 broadcast_typists
19 end
20 
21 def stop_typing
22 Rails.cache.delete(typing_key)
23 broadcast_typists
24 end
25 
26 private
27 
28 def sweep_stale_typists
29 broadcast_typists unless Rails.cache.exist?(typing_key)
30 end
31 
32 def broadcast_typists
33 names = active_typists.reject { |name| name == current_user.name }
34 
35 ChatChannel.broadcast_to @room, type: "typing", users: names
36 end
37 
38 def active_typists
39 Rails.cache.read_multi(*typing_keys_for_room).values.compact
40 end
41 
42 def typing_keys_for_room
43 @room.membership_user_ids.map { |id| "room:#{@room.id}:typing:#{id}" }
44 end
45 
46 def typing_key
47 "room:#{@room.id}:typing:#{current_user.id}"
48 end
49end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Expiring cache keys give you self-cleaning presence state without a background job or database table.
  2. 2A periodic timer paired with a key existence check lets clients recover from missed stop events.
  3. 3Broadcasting the full recomputed list on every change keeps every subscriber's view consistent.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a typing indicator works in Rails ActionCable — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code