Class: Schematic::DataStream::ResourceCache

Inherits:
Object
  • Object
show all
Defined in:
lib/schematic/datastream/resource_cache.rb

Constant Summary collapse

CACHE_KEY_PREFIX =
"schematic"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(primary_cache:, lookup_cache:, key_prefix:, get_id:, get_keys:, cache_version: nil) ⇒ ResourceCache

Returns a new instance of ResourceCache.



8
9
10
11
12
13
14
15
# File 'lib/schematic/datastream/resource_cache.rb', line 8

def initialize(primary_cache:, lookup_cache:, key_prefix:, get_id:, get_keys:, cache_version: nil)
  @primary_cache = primary_cache
  @lookup_cache = lookup_cache
  @key_prefix = key_prefix
  @get_id = get_id
  @get_keys = get_keys
  @cache_version = cache_version || ""
end

Instance Attribute Details

#cache_version=(value) ⇒ Object (writeonly)

Sets the attribute cache_version

Parameters:

  • value

    the value to set the attribute cache_version to.



17
18
19
# File 'lib/schematic/datastream/resource_cache.rb', line 17

def cache_version=(value)
  @cache_version = value
end

Instance Method Details

#cache_entity(entity, ttl: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/schematic/datastream/resource_cache.rb', line 19

def cache_entity(entity, ttl: nil)
  id = @get_id.call(entity)
  return unless id

  id_key = build_id_key(id)
  @primary_cache.set(id_key, entity, ttl: ttl)

  keys = @get_keys.call(entity)
  keys&.each do |k, v|
    lookup_key = build_lookup_key(k, v)
    @lookup_cache.set(lookup_key, id, ttl: ttl)
  end
end

#delete_entity(entity) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/schematic/datastream/resource_cache.rb', line 53

def delete_entity(entity)
  id = @get_id.call(entity)
  return unless id

  @primary_cache.delete(build_id_key(id))

  keys = @get_keys.call(entity)
  keys&.each do |k, v|
    @lookup_cache.delete(build_lookup_key(k, v))
  end
end

#get_by_id(id) ⇒ Object



33
34
35
36
37
# File 'lib/schematic/datastream/resource_cache.rb', line 33

def get_by_id(id)
  id_key = build_id_key(id)
  entity = @primary_cache.get(id_key)
  entity ? Merge.deep_copy(entity) : nil
end

#get_by_keys(keys) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/schematic/datastream/resource_cache.rb', line 39

def get_by_keys(keys)
  return nil unless keys&.any?

  keys.each do |k, v|
    lookup_key = build_lookup_key(k, v)
    id = @lookup_cache.get(lookup_key)
    if id
      entity = get_by_id(id)
      return entity if entity
    end
  end
  nil
end