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.
8 9 10 |
# File 'lib/httpdisk/cache.rb', line 8 def initialize() @options = end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
6 7 8 |
# File 'lib/httpdisk/cache.rb', line 6 def @options end |
Instance Method Details
#delete(cache_key) ⇒ Object
Delete existing response, if any
54 55 56 57 |
# File 'lib/httpdisk/cache.rb', line 54 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
60 61 62 |
# File 'lib/httpdisk/cache.rb', line 60 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.
21 22 23 24 |
# File 'lib/httpdisk/cache.rb', line 21 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]
27 28 29 30 31 32 |
# File 'lib/httpdisk/cache.rb', line 27 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
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/httpdisk/cache.rb', line 35 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 |