class WeatherSage::Cache
Minimal cache implementation.
Public Class Methods
new(path)
click to toggle source
Create a new Cache
instance bound to file at path path
.
# File lib/weather-sage/cache.rb, line 10 def initialize(path) @pstore = ::PStore.new(path) end
Public Instance Methods
delete(key)
click to toggle source
Delete entry in cache with key key
.
# File lib/weather-sage/cache.rb, line 60 def delete(key) @pstore.transaction do @pstore.delete(key) end end
get(key)
click to toggle source
Get entry in cache with key key
.
Returns nil if no such entry exists.
# 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
Also aliased as: []
key?(key)
click to toggle source
Returns true if the key exists and is it still valid.
# 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)
click to toggle source
Set entry in cache with key key
to value val
.
An optional timeout (in seconds) may be provided with timout
.
# 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
Also aliased as: []=
Private Instance Methods
flush()
click to toggle source
Purge expired entries.
# File lib/weather-sage/cache.rb, line 74 def flush @pstore.roots.each do |key| @pstore.delete(key) unless @pstore[key].valid? end end