class Chatbox::MemcachedStore

Attributes

client[R]
id_generator[R]

Public Class Methods

new(client, id_generator: -> { SecureRandom.uuid } click to toggle source
# File lib/chatbox/memcached_store.rb, line 6
def initialize(client, id_generator: -> { SecureRandom.uuid })
  @client = client
  @id_generator = id_generator
end

Public Instance Methods

add_message(attrs) click to toggle source
# File lib/chatbox/memcached_store.rb, line 11
def add_message(attrs)
  id = id_generator.()

  write "messages/#{id}", {
    from_id: attrs[:from_id],
    to_id: attrs[:to_id],
    body: attrs[:body],
    read: false,
  }

  from_list = read("from/#{attrs[:from_id]}") || []
  from_list << {from_id: attrs[:from_id], message_id: id}
  write "from/#{attrs[:from_id]}", from_list

  to_list = read("to/#{attrs[:to_id]}") || []
  to_list << {to_id: attrs[:to_id], message_id: id}
  write "to/#{attrs[:to_id]}", to_list
end
find_message(id) click to toggle source
# File lib/chatbox/memcached_store.rb, line 46
def find_message(id)
  if attrs = read("messages/#{id}")
    Record.new id, attrs
  end
end
find_messages_by_from_id(id) click to toggle source
# File lib/chatbox/memcached_store.rb, line 62
def find_messages_by_from_id(id)
  if attrs_list = read("from/#{id}")
    attrs_list.map do |attrs|
      find_message attrs[:message_id]
    end
  else
    []
  end
end
find_messages_by_to_id(id) click to toggle source
# File lib/chatbox/memcached_store.rb, line 52
def find_messages_by_to_id(id)
  if attrs_list = read("to/#{id}")
    attrs_list.map do |attrs|
      find_message attrs[:message_id]
    end
  else
    []
  end
end
mark_message_read!(id) click to toggle source
# File lib/chatbox/memcached_store.rb, line 32
def mark_message_read!(id)
  attrs = read "messages/#{id}"
  attrs[:read] = true
  write "messages/#{id}", attrs
end
mark_message_unread!(id) click to toggle source
# File lib/chatbox/memcached_store.rb, line 38
def mark_message_unread!(id)
  attrs = read "messages/#{id}"
  attrs[:read] = false
  write "messages/#{id}", attrs
end

Private Instance Methods

read(key) click to toggle source
# File lib/chatbox/memcached_store.rb, line 76
def read(key)
  if value = client.get(key)
    JSON.parse value, symbolize_names: true
  end
end
write(key, value) click to toggle source
# File lib/chatbox/memcached_store.rb, line 82
def write(key, value)
  client.set key, JSON.generate(value)
end