class Prismic::LruCache
This is a simple cache class provided with the prismic.io Ruby kit.
It is pretty dumb but effective: * everything is stored in memory,
If you need a smarter caching (for instance, rely on memcached), you can extend this class and replace its methods, and when creating your API
object like this for instance: Prismic.api
(url, options), pass the name of the class you created as a :cache option. Therefore, to use this simple cache, you can create your API
object like this: `Prismic.api(url, cache: Prismic::DefaultCache)`
Attributes
@return [LRUHash<String,Object>]
Public Class Methods
@param max_size [Fixnum] (100) The default maximum of keys to store
# File lib/prismic/cache/lru.rb, line 22 def initialize(max_size=100) @intern = Hashery::LRUHash.new(max_size) end
Public Instance Methods
# File lib/prismic/cache/lru.rb, line 37 def []=(key, value) set(key, value, nil) end
# File lib/prismic/cache/lru.rb, line 60 def delete(key) @intern.delete(key) nil end
# File lib/prismic/cache/lru.rb, line 75 def expired?(key) if include?(key) && @intern[key][:expired_in] != nil expired_in = @intern[key][:expired_in] expired_in && expired_in < Time.now.getutc.to_i else false end end
Get a cache entry
@param key [String] The key to fetch
@return [Object] The cache object as was stored
# File lib/prismic/cache/lru.rb, line 46 def get(key) return delete(key) if expired?(key) include?(key) ? @intern[key][:data] : nil end
# File lib/prismic/cache/lru.rb, line 52 def get_or_set(key, value = nil, expired_in = nil) if include?(key) && !expired?(key) return get(key) else set(key, block_given? ? yield : value, expired_in) end end
Checks if a cache entry exists
@param key [String] The key to test
@return [Boolean]
# File lib/prismic/cache/lru.rb, line 70 def has_key?(key) @intern.has_key?(key) end
Invalidates all entries
# File lib/prismic/cache/lru.rb, line 85 def invalidate_all! @intern.clear end
Expose the Hash keys
This is only for debugging purposes.
@return [Array<String>]
# File lib/prismic/cache/lru.rb, line 95 def keys @intern.keys end
Add a cache entry.
@param key [String] The key @param value [Object] The value to store
@return [Object] The stored value
# File lib/prismic/cache/lru.rb, line 32 def set(key, value, expired_in = nil) @intern.store(key, { :data => value, :expired_in => expired_in = expired_in && Time.now.getutc.to_i + expired_in }) value end
Return the number of stored keys
@return [Fixum]
# File lib/prismic/cache/lru.rb, line 102 def size @intern.size end