Module: PolyId::Cache

Defined in:
lib/polyid/cache.rb

Class Method Summary collapse

Class Method Details

.delete(model_name, id:, uuid:) ⇒ Object



60
61
62
# File 'lib/polyid/cache.rb', line 60

def delete(model_name, id:, uuid:)
  delete_multi(model_name, ids: [id], uuids: [uuid])
end

.delete_multi(model_name, ids: [], uuids: []) ⇒ Object



64
65
66
67
68
69
# File 'lib/polyid/cache.rb', line 64

def delete_multi(model_name, ids: [], uuids: [])
  keys = ids.map { |id| id_key(model_name, id) } +
    uuids.map { |uuid| uuid_key(model_name, uuid) }

  PolyId.cache.delete_multi(keys)
end

.fetch_ids(model_name, uuids:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/polyid/cache.rb', line 27

def fetch_ids(model_name, uuids:)
  cached_ids = read_multi(model_name, uuids: uuids)[:uuids]
  missing_uuids = uuids - cached_ids.keys

  if missing_uuids.any?
    yielded_ids = yield(missing_uuids)
    cached_ids.merge!(yielded_ids)
  end

  cached_ids
end

.fetch_uuids(model_name, ids:) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/polyid/cache.rb', line 39

def fetch_uuids(model_name, ids:)
  cached_uuids = read_multi(model_name, ids: ids)[:ids]
  missing_ids = ids - cached_uuids.keys

  if missing_ids.any?
    yielded_uuids = yield(missing_ids)
    cached_uuids.merge!(yielded_uuids)
  end

  cached_uuids
end

.read(model_name, id: nil, uuid: nil) ⇒ Object



4
5
6
7
8
# File 'lib/polyid/cache.rb', line 4

def read(model_name, id: nil, uuid: nil)
  value = PolyId.cache.read(id.nil? ? uuid_key(model_name, uuid) : id_key(model_name, id))

  id.nil? ? value : decode_uuid(value)
end

.read_multi(model_name, ids: [], uuids: []) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/polyid/cache.rb', line 10

def read_multi(model_name, ids: [], uuids: [])
  id_keys = ids.to_h { |id| [id, id_key(model_name, id)] }
  uuid_keys = uuids.to_h { |uuid| [uuid, uuid_key(model_name, uuid)] }
  keys = id_keys.values + uuid_keys.values

  cached = PolyId.cache.read_multi(*keys)

  {
    ids: id_keys.each_with_object({}) do |(id, cache_key), values|
      values[id] = decode_uuid(cached[cache_key]) if cached.key?(cache_key)
    end,
    uuids: uuid_keys.each_with_object({}) do |(uuid, cache_key), values|
      values[uuid] = cached[cache_key] if cached.key?(cache_key)
    end,
  }
end

.write(model_name, id:, uuid:) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/polyid/cache.rb', line 51

def write(model_name, id:, uuid:)
  encoded_uuid = encode_uuid(uuid)

  PolyId.cache.write_multi(
    id_key(model_name, id) => encoded_uuid,
    uuid_key(model_name, uuid, encoded_uuid) => id,
  )
end