class Cache
Simple cache for HTTP(S) text files
Attributes
Is the cache enabled?
Don’t bother checking cache entries that are younger (seconds)
Public Class Methods
Source
# 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
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
Public Instance Methods
Source
# File lib/whimsy/cache.rb, line 34 def enabled=(enabled) @enabled = enabled init_cache(@dir) if enabled end
enable the cache
Source
# 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 cond['If-None-Match'] = etag 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) if res.is_a?(Net::HTTPSuccess) write_cache(url, res) return uri, res.body, data ? 'no last mod/etag' : 'cachemiss' else return nil, res, 'error' end end end
gets the URL content
Caches the response and returns that if unchanged or recent
Returns:
-
uri (after redirects)
-
content - or response if status is error
-
status: nocache, recent, updated, unchanged, error, cachemiss or no last mod/etag