Class: Gemmy::Components::Cache

Inherits:
Hash
  • Object
show all
Defined in:
lib/gemmy/components/cache.rb

Constant Summary collapse

CachePath =
ENV["GEMMY_CACHE_PATH"] || "#{home}/gemmy/caches"

Instance Method Summary collapse

Constructor Details

#initialize(db_name) ⇒ Cache

Returns a new instance of Cache.



13
14
15
16
# File 'lib/gemmy/components/cache.rb', line 13

def initialize(db_name)
  @db = {}.persisted "#{CachePath}/#{db_name}.yaml"
  @memory = @db.get(:data)
end

Instance Method Details

#clearObject



45
46
47
48
# File 'lib/gemmy/components/cache.rb', line 45

def clear
  # forwards it to PersistedHash
  @db.clear
end

#get(*keys, source: :db) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/gemmy/components/cache.rb', line 31

def get(*keys, source: :db)
  if source == :memory
    @memory.dig *keys
  elsif source == :db
    @db.dig *keys
  else
    raise ArgumentError
  end
end

#get_or_set(*keys, &blk) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/gemmy/components/cache.rb', line 18

def get_or_set(*keys, &blk)
  result = get(*keys)
  if result.blank?
    result = blk.call
    set(*keys, result)
  end
  result
end

#keysObject



27
28
29
# File 'lib/gemmy/components/cache.rb', line 27

def keys
  @db.data.keys
end

#set(*keys, val) ⇒ Object



41
42
43
# File 'lib/gemmy/components/cache.rb', line 41

def set(*keys, val)
  @db.set(*keys, val)
end