Class: SimpleCache::MemoryCache
- Inherits:
-
Object
- Object
- SimpleCache::MemoryCache
- Defined in:
- lib/simple_cache.rb
Overview
TODO: add a super-class and implement FileSystemCache
Instance Attribute Summary collapse
-
#cache_size ⇒ Object
readonly
Returns the value of attribute cache_size.
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #delete(key) ⇒ Object
- #encode(key) ⇒ Object
- #has_key?(key) ⇒ Boolean
-
#initialize(options = {}) ⇒ MemoryCache
constructor
A new instance of MemoryCache.
- #prune ⇒ Object
- #stale?(key) ⇒ Boolean
Constructor Details
#initialize(options = {}) ⇒ MemoryCache
Returns a new instance of MemoryCache.
32 33 34 35 36 37 38 |
# File 'lib/simple_cache.rb', line 32 def initialize( = {}) @cache = {} @cache_size = 0 @key_access = {} @max_size = [:max_size] || 32 * 1024 #32 megabytes @timeout = [:timeout] || 60*30 #30 minutes end |
Instance Attribute Details
#cache_size ⇒ Object (readonly)
Returns the value of attribute cache_size.
30 31 32 |
# File 'lib/simple_cache.rb', line 30 def cache_size @cache_size end |
Instance Method Details
#[](key) ⇒ Object
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/simple_cache.rb', line 50 def [](key) key = encode(key) entry = @cache[key] if entry @key_access[key] = Time.now.to_f else @key_access.delete key end entry end |
#[]=(key, value) ⇒ Object
61 62 63 64 65 66 67 68 69 |
# File 'lib/simple_cache.rb', line 61 def []=(key, value) key = encode(key) old_entry = @cache[key] @cache_size -= old_entry.size if old_entry @key_access[key] = Time.now.to_f @cache[key] = value @cache_size += value.size prune if @cache_size > @max_size end |
#delete(key) ⇒ Object
44 45 46 47 48 |
# File 'lib/simple_cache.rb', line 44 def delete(key) entry = @cache.delete key @key_access.delete key @cache_size -= entry.size end |
#encode(key) ⇒ Object
40 41 42 |
# File 'lib/simple_cache.rb', line 40 def encode(key) Digest::MD5.hexdigest key end |
#has_key?(key) ⇒ Boolean
71 72 73 |
# File 'lib/simple_cache.rb', line 71 def has_key?(key) !!@cache[encode(key)] end |
#prune ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/simple_cache.rb', line 75 def prune #first, the obvious cleanup @cache.keys.each do |key| delete(key) if stale? key end #now, try to leave it a 3/4 of it's capacity target_size = 0.75 * @max_size #delete the older entries sorted_keys = @key_access.keys.sort{|a,b| @key_access[a].to_f <=> @key_access[b].to_f} sorted_keys.each do |key| return if @cache_size <= target_size delete key end end |
#stale?(key) ⇒ Boolean
92 93 94 |
# File 'lib/simple_cache.rb', line 92 def stale?(key) (Time.now.to_f - @key_access[key]) > @timeout.to_f end |