Class: WeatherSage::Cache
- Inherits:
-
Object
- Object
- WeatherSage::Cache
- Defined in:
- lib/weather-sage/cache.rb
Overview
Minimal cache implementation.
Instance Method Summary collapse
-
#delete(key) ⇒ Object
Delete entry in cache with key
key. -
#get(key) ⇒ Object
(also: #[])
Get entry in cache with key
key. -
#initialize(path) ⇒ Cache
constructor
Create a new Cache instance bound to file at path
path. -
#key?(key) ⇒ Boolean
Returns true if the key exists and is it still valid.
-
#set(key, val, timeout = nil) ⇒ Object
(also: #[]=)
Set entry in cache with key
keyto valueval.
Constructor Details
#initialize(path) ⇒ Cache
Create a new Cache instance bound to file at path path.
10 11 12 |
# File 'lib/weather-sage/cache.rb', line 10 def initialize(path) @pstore = ::PStore.new(path) end |
Instance Method Details
#delete(key) ⇒ Object
Delete entry in cache with key key.
60 61 62 63 64 |
# File 'lib/weather-sage/cache.rb', line 60 def delete(key) @pstore.transaction do @pstore.delete(key) end end |
#get(key) ⇒ Object Also known as: []
Get entry in cache with key key.
Returns nil if no such entry exists.
50 51 52 53 54 55 |
# File 'lib/weather-sage/cache.rb', line 50 def get(key) @pstore.transaction(true) do return nil unless entry = @pstore[key] entry.valid? ? entry.value : nil end end |
#key?(key) ⇒ Boolean
Returns true if the key exists and is it still valid.
17 18 19 20 21 22 |
# File 'lib/weather-sage/cache.rb', line 17 def key?(key) @pstore.transaction(true) do return false unless entry = @pstore[key] entry.valid? end end |
#set(key, val, timeout = nil) ⇒ Object Also known as: []=
Set entry in cache with key key to value val.
An optional timeout (in seconds) may be provided with timout.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/weather-sage/cache.rb', line 29 def set(key, val, timeout = nil) @pstore.transaction do # calculate expiration time expires = timeout ? (Time.now.to_i + timeout) : nil # save entry @pstore[key] = ::WeatherSage::CacheEntry.new(expires, val) # purge any expired entries flush end # return value val end |