class Cache

A simple file caching mechanism with automatic timeout.

Public Class Methods

new(cache, timeout=24) click to toggle source

Create a cache at cache path for a given timeout (in hours).

# File lib/dep_analyzer.rb, line 13
def initialize(cache, timeout=24)
  @cache = cache
  @timeout = timeout
end

Public Instance Methods

cache(id, timeout=@timeout) { || ... } click to toggle source

Add a cached item to id. Value is returned either from the cache if it is new enough or by yielding.

# File lib/dep_analyzer.rb, line 22
def cache(id, timeout=@timeout)
  Dir.mkdir @cache unless test ?d, @cache
  path = File.join @cache, id

  age = test(?f, path) ? (Time.now - test( ?M, path )) / 3600 : -1

  if age >= 0 and timeout > age then
    warn "from cache" if $DEBUG
    data = File.read(path)
  else
    warn "NOT from cache (#{age} hours old)" if $DEBUG
    data = yield
    File.open(path, "w") do |f|
      f.write data
    end
  end
  return data
end