Class: FileCache

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

Overview

A file-based caching library. It uses Marshal::dump and Marshal::load to serialize/deserialize cache values - so you should be OK to cache object values.

Constant Summary collapse

MAX_DEPTH =
32

Instance Method Summary collapse

Constructor Details

#initialize(domain = "default", root_dir = "/tmp", expiry = 0, depth = 2) ⇒ FileCache

Create a new reference to a file cache system.

domain

A string that uniquely identifies this caching system on the given host

root_dir

The root directory of the cache file hierarchy The cache will be rooted at root_dir/domain/

expiry

The expiry time for cache entries, in seconds. Use 0 if you want cached values never to expire.

depth

The depth of the file tree storing the cache. Should be large enough that no cache directory has more than a couple of hundred objects in it



21
22
23
24
25
26
27
# File 'lib/filecache.rb', line 21

def initialize(domain = "default", root_dir = "/tmp", expiry = 0, depth = 2)
  @domain  = domain
  @root_dir = root_dir
  @expiry  = expiry
  @depth   = depth > MAX_DEPTH ? MAX_DEPTH : depth
  FileUtils.mkdir_p(get_root)
end

Instance Method Details

#clearObject

Delete ALL data from the cache, regardless of expiry time



63
64
65
66
67
68
# File 'lib/filecache.rb', line 63

def clear
  if File.exists?(get_root)
    FileUtils.rm_r(get_root)
    FileUtils.mkdir_p(get_root)
  end
end

#delete(key) ⇒ Object

Delete the value for the given key from the cache



58
59
60
# File 'lib/filecache.rb', line 58

def delete(key)
  FileUtils.rm(get_path(key))
end

#get(key) ⇒ Object

Return the value for the specified key from the cache. Returns nil if the value isn’t found.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/filecache.rb', line 39

def get(key)
  path = get_path(key)

  # expire
  if @expiry > 0 && File.exists?(path) && Time.new - File.new(path).mtime >= @expiry
    FileUtils.rm(path)
  end
  
  if File.exists?(path)
    f = File.open(path, "r")
    result = Marshal.load(f)
    f.close
    return result
  else
    return nil
  end
end

#purgeObject

Delete all expired data from the cache



71
72
73
74
# File 'lib/filecache.rb', line 71

def purge
  @t_purge = Time.new
  purge_dir(get_root) if @expiry > 0
end

#set(key, value) ⇒ Object

Set a cache value for the given key. If the cache contains an existing value for the key it will be overwritten.



31
32
33
34
35
# File 'lib/filecache.rb', line 31

def set(key, value)
  f = File.open(get_path(key), "w")
  Marshal.dump(value, f)
  f.close
end