class Cache

Simple cache for HTTP(S) text files

Attributes

enabled[R]

Is the cache enabled?

minage[RW]

Don't bother checking cache entries that are younger (seconds)

Public Class Methods

new(dir: '/tmp/whimsy-cache', minage: 3000, enabled: true) click to toggle source

Create the cache

Parameters:

  • dir - where to store the files. Path is relative to '/tmp/whimsy-cache'

  • minage - don't check remote copy if the file is newer than this number of seconds

  • enabled - is the cache enabled initially

# File lib/whimsy/cache.rb, line 20
def initialize(dir: '/tmp/whimsy-cache',
      minage: 3000, # 50 mins
      enabled: true)
  if dir.start_with?('/')
    @dir = dir
  else
    @dir = File.join('/tmp/whimsy-cache', dir)
  end
  @enabled = enabled
  @minage = minage
  init_cache(@dir) if enabled
end

Public Instance Methods

enabled=(enabled) click to toggle source

enable the cache

# File lib/whimsy/cache.rb, line 34
def enabled=(enabled)
  @enabled = enabled
  init_cache(@dir) if enabled
end
get(url) click to toggle source

gets the URL content

Caches the response and returns that if unchanged or recent

Returns:

  • uri (after redirects)

  • content

  • status: nocache, recent, updated, missing or no last mod/etag

# File lib/whimsy/cache.rb, line 47
def get(url)
  if not @enabled
    uri, res = fetch(url)
    return uri, res.body, 'nocache'
  end

  # Check the cache
  age, lastmod, uri, etag, data = read_cache(url)
  Wunderbar.debug "#{uri} #{age} LM=#{lastmod} ET=#{etag}"
  if age < minage
    return uri, data, 'recent' # we have a recent cache entry
  end

  # Try to do a conditional get
  if data and (lastmod or etag)
    cond = {}
    cond['If-Modified-Since'] = lastmod if lastmod
    # Allow for Apache Bug 45023
    cond['If-None-Match'] = etag.gsub(/-gzip"$/,'"') if etag
    uri, res = fetch(url, cond)
    if res.is_a?(Net::HTTPSuccess)
      write_cache(url, res)
      return uri, res.body, 'updated'
    elsif res.is_a?(Net::HTTPNotModified)
      path = makepath(url)
      mtime = Time.now
      File.utime(mtime, mtime, path) # show we checked the page
      return uri, data, 'unchanged'
    else
      return nil, res, 'error'
    end
  else
    uri, res = fetch(url)
    write_cache(url, res)
    return uri, res.body, data ? 'no last mod/etag' : 'missing'
  end
end