Module: Cache

Defined in:
lib/lydown/cache.rb

Constant Summary collapse

CACHE_DIR =
"/tmp/lydown/cache"

Class Method Summary collapse

Class Method Details

.calculate_hash(*params) ⇒ Object



27
28
29
30
31
# File 'lib/lydown/cache.rb', line 27

def calculate_hash(*params)
  params.map do |p|
    Digest::MD5.hexdigest(p.is_a?(String) ? p : p.to_s)
  end.join('-')
end

.disable!Object



6
7
8
# File 'lib/lydown/cache.rb', line 6

def disable!
  @disabled = true
end

.enable!Object



10
11
12
# File 'lib/lydown/cache.rb', line 10

def enable!
  @disabled = false
end

.filename(cache_key) ⇒ Object



53
54
55
# File 'lib/lydown/cache.rb', line 53

def filename(cache_key)
  "#{CACHE_DIR}/#{cache_key}"
end

.get(cache_key) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/lydown/cache.rb', line 33

def get(cache_key)
  fn = filename(cache_key)
  if File.file?(fn)
    Marshal.load(IO.read(fn))
  else
    nil
  end
rescue
  nil
end

.hit(*params) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/lydown/cache.rb', line 14

def hit(*params)
  return yield if @disabled
  
  cache_key = calculate_hash(*params)
  if result = get(cache_key)
    result
  else
    result = yield
    set(cache_key, result)
    result
  end
end

.set(cache_key, value) ⇒ Object



44
45
46
47
48
# File 'lib/lydown/cache.rb', line 44

def set(cache_key, value)
  File.open(filename(cache_key), 'w+') do |f|
    f << Marshal.dump(value)
  end
end