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
-
#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 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/httpdisk/cache.rb', line 8 def initialize() @options = # heavy sanity checking on arguments here if !dir.is_a?(String) raise ArgumentError, "expected :dir to be a string, not #{dir.inspect}" end if expires_in && !expires_in.is_a?(Integer) raise ArgumentError, "expected :expires_in to be an integer, not #{expires_in.inspect}" end %i[force force_errors].each do value = send(_1) if ![nil, true, false].include?(value) raise ArgumentError, "expected #{_1} to be a boolean, not #{value.inspect}" end end 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
#diskpath(cache_key) ⇒ Object
Relative path for this cache_key based on the cache key
57 58 59 |
# File 'lib/httpdisk/cache.rb', line 57 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.
36 37 38 39 |
# File 'lib/httpdisk/cache.rb', line 36 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]
42 43 44 45 46 47 |
# File 'lib/httpdisk/cache.rb', line 42 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_999? ? :error : :hit end |
#write(cache_key, payload) ⇒ Object
Write response to the disk cache
50 51 52 53 54 |
# File 'lib/httpdisk/cache.rb', line 50 def write(cache_key, payload) path = diskpath(cache_key) FileUtils.mkdir_p(File.dirname(path)) Zlib::GzipWriter.open(path) { payload.write(_1) } end |