Class: TurboPresence::PresenceStore
- Inherits:
-
Object
- Object
- TurboPresence::PresenceStore
- Defined in:
- lib/turbo_presence/presence_store.rb
Instance Method Summary collapse
-
#all(room) ⇒ Object
Returns hash of { user_id => identity_hash } for a room.
-
#initialize(redis: nil, ttl: 60) ⇒ PresenceStore
constructor
A new instance of PresenceStore.
- #join(room, user_id, identity) ⇒ Object
- #leave(room, user_id) ⇒ Object
- #touch(room, _user_id) ⇒ Object
- #update_cursor(room, user_id, x:, y:) ⇒ Object
Constructor Details
#initialize(redis: nil, ttl: 60) ⇒ PresenceStore
Returns a new instance of PresenceStore.
5 6 7 8 9 10 |
# File 'lib/turbo_presence/presence_store.rb', line 5 def initialize(redis: nil, ttl: 60) @redis = redis @ttl = ttl @memory = {} @mutex = Mutex.new end |
Instance Method Details
#all(room) ⇒ Object
Returns hash of { user_id => identity_hash } for a room
13 14 15 16 17 18 19 20 |
# File 'lib/turbo_presence/presence_store.rb', line 13 def all(room) if @redis entries = @redis.hgetall(redis_key(room)) entries.transform_values { |v| JSON.parse(v, symbolize_names: true) } else @mutex.synchronize { (@memory[room] || {}).dup } end end |
#join(room, user_id, identity) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/turbo_presence/presence_store.rb', line 22 def join(room, user_id, identity) if @redis @redis.hset(redis_key(room), user_id.to_s, identity.to_json) @redis.expire(redis_key(room), @ttl) else @mutex.synchronize do @memory[room] ||= {} @memory[room][user_id.to_s] = identity end end end |
#leave(room, user_id) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/turbo_presence/presence_store.rb', line 34 def leave(room, user_id) if @redis @redis.hdel(redis_key(room), user_id.to_s) else @mutex.synchronize { @memory[room]&.delete(user_id.to_s) } end end |
#touch(room, _user_id) ⇒ Object
63 64 65 |
# File 'lib/turbo_presence/presence_store.rb', line 63 def touch(room, _user_id) @redis&.expire(redis_key(room), @ttl) end |
#update_cursor(room, user_id, x:, y:) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/turbo_presence/presence_store.rb', line 42 def update_cursor(room, user_id, x:, y:) if @redis raw = @redis.hget(redis_key(room), user_id.to_s) return unless raw identity = JSON.parse(raw, symbolize_names: true) identity[:cursor_x] = x identity[:cursor_y] = y @redis.hset(redis_key(room), user_id.to_s, identity.to_json) @redis.expire(redis_key(room), @ttl) else @mutex.synchronize do entry = @memory.dig(room, user_id.to_s) return unless entry entry[:cursor_x] = x entry[:cursor_y] = y end end end |