class Cache
Simple cache for HTTP(S) text files
Constants
- CSP_PREFIX
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 22 def initialize(dir: '/tmp/whimsy-cache', minage: 3000, # 50 mins enabled: true, save_csp: false) if dir.start_with?('/') @dir = dir else @dir = File.join('/tmp/whimsy-cache', dir) end @enabled = enabled @minage = minage @save_csp = save_csp 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 38 def enabled=(enabled) @enabled = enabled init_cache(@dir) if enabled end
enable the cache
Source
# File lib/whimsy/cache.rb, line 51 def get(url) if not @enabled uri, res = fetch(url) if @save_csp return uri, res.body, 'nocache', res.header['content-security-policy'] else return uri, res.body, 'nocache' end end # Check the cache age, lastmod, uri, etag, data, csp = read_cache(url) Wunderbar.debug "#{uri} #{age} LM=#{lastmod} ET=#{etag}" if age < minage if @save_csp return uri, data, 'recent', csp # we have a recent cache entry else return uri, data, 'recent' # we have a recent cache entry end end # Try to do a conditional get (unless csp is missing) if data and (lastmod or etag) and (csp or !@save_csp) 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) if @save_csp return uri, res.body, 'updated', res.header['content-security-policy'] else return uri, res.body, 'updated' end elsif res.is_a?(Net::HTTPNotModified) path = makepath(url) mtime = Time.now File.utime(mtime, mtime, path) # show we checked the page if @save_csp return uri, data, 'unchanged', csp else return uri, data, 'unchanged' end else return nil, res, 'error' end else uri, res = fetch(url) if res.is_a?(Net::HTTPSuccess) write_cache(url, res) if @save_csp return uri, res.body, data ? 'no last mod/etag' : 'cachemiss', res.header['content-security-policy'] else return uri, res.body, data ? 'no last mod/etag' : 'cachemiss' end 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