Class: HTTPDisk::Cache
- Inherits:
-
Object
- Object
- HTTPDisk::Cache
- Defined in:
- lib/httpdisk/cache.rb
Overview
Disk cache for cache_keys => response. Files are compressed.
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
-
#delete(cache_key) ⇒ Object
Delete existing response, if any.
-
#diskpath(cache_key) ⇒ Object
Relative path for this cache_key based on the cache key.
-
#initialize(options) ⇒ Cache
constructor
A new instance of Cache.
-
#read(cache_key) ⇒ Object
Get cached response.
-
#status(cache_key) ⇒ Object
Cache status for a cache_key, %i[error force hit miss stale].
-
#write(cache_key, payload) ⇒ Object
Write response to the disk cache.
Constructor Details
#initialize(options) ⇒ Cache
Returns a new instance of Cache.
9 10 11 |
# File 'lib/httpdisk/cache.rb', line 9 def initialize() @options = end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
7 8 9 |
# File 'lib/httpdisk/cache.rb', line 7 def @options end |
Instance Method Details
#delete(cache_key) ⇒ Object
Delete existing response, if any
55 56 57 58 |
# File 'lib/httpdisk/cache.rb', line 55 def delete(cache_key) path = diskpath(cache_key) FileUtils.rm(path) if File.exist?(path) end |
#diskpath(cache_key) ⇒ Object
Relative path for this cache_key based on the cache key
61 62 63 |
# File 'lib/httpdisk/cache.rb', line 61 def diskpath(cache_key) File.join(dir, cache_key.diskpath) end |
#read(cache_key) ⇒ Object
Get cached response. If there is a cached error it will be raised.
22 23 24 25 |
# File 'lib/httpdisk/cache.rb', line 22 def read(cache_key) payload_or_status = read0(cache_key) payload_or_status.is_a?(Symbol) ? nil : payload_or_status end |
#status(cache_key) ⇒ Object
Cache status for a cache_key, %i[error force hit miss stale]
28 29 30 31 32 33 |
# File 'lib/httpdisk/cache.rb', line 28 def status(cache_key) payload_or_status = read0(cache_key, peek: true) return payload_or_status if payload_or_status.is_a?(Symbol) payload_or_status.error? ? :error : :hit end |
#write(cache_key, payload) ⇒ Object
Write response to the disk cache
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/httpdisk/cache.rb', line 36 def write(cache_key, payload) path = diskpath(cache_key) FileUtils.mkdir_p(File.dirname(path)) # Atomically write gzipped payload. Put our underlying Tempfile into # binmode to avoid accidental newline conversion or string encoding. Not # required for *nix systems, but I've heard rumors it's helpful for # Windows. Tempfile.new(binmode: true).tap do |tmp| Zlib::GzipWriter.new(tmp).tap do |gzip| payload.write(gzip) gzip.close end tmp.close FileUtils.mv(tmp.path, path) end end |