Class: Schlib::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/schlib/cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache_file = '/tmp/schlib_cache.tmp') ⇒ Cache

Returns a new instance of Cache.



7
8
9
# File 'lib/schlib/cache.rb', line 7

def initialize(cache_file = '/tmp/schlib_cache.tmp')
  @cache_file = cache_file
end

Instance Method Details

#cache(cache_key) ⇒ Object



11
12
13
14
15
16
# File 'lib/schlib/cache.rb', line 11

def cache(cache_key)
  mutable_cache_data = data
  thing = mutable_cache_data[cache_key.to_s] ||= yield
  File.write cache_file, JSON.dump(mutable_cache_data)
  thing
end

#clearObject



29
30
31
# File 'lib/schlib/cache.rb', line 29

def clear
  File.delete cache_file
end

#dataObject



18
19
20
21
# File 'lib/schlib/cache.rb', line 18

def data
  File.write cache_file, JSON.dump({}) unless File.exist? cache_file
  JSON.parse File.read cache_file
end

#reset(key) ⇒ Object



23
24
25
26
27
# File 'lib/schlib/cache.rb', line 23

def reset(key)
  mutable_cache_data = data
  mutable_cache_data[key.to_s] = nil
  File.write cache_file, JSON.dump(mutable_cache_data)
end