Class: Cache::StorageCache
Overview
Implements a cache using a parameterizable strategy and a storage. The protocol that the store must understand is:
fetch(key) -> val
has_key?(key)
delete(key) -> val
each {|key, val| }
Direct Known Subclasses
Instance Method Summary collapse
- #delete(key) ⇒ Object
- #fetch(key, default_value = nil) ⇒ Object (also: #[])
- #has_key?(key) ⇒ Boolean
-
#initialize(strategy, store = Hash.new, store_on_update = false) ⇒ StorageCache
constructor
A new instance of StorageCache.
- #store(key, value) ⇒ Object (also: #[]=)
Constructor Details
#initialize(strategy, store = Hash.new, store_on_update = false) ⇒ StorageCache
Returns a new instance of StorageCache.
114 115 116 117 118 |
# File 'lib/cache/cache.rb', line 114 def initialize(strategy, store=Hash.new, store_on_update=false) @strategy = strategy @store = store @store_on_update = store_on_update end |
Instance Method Details
#delete(key) ⇒ Object
124 125 126 127 128 129 130 131 132 |
# File 'lib/cache/cache.rb', line 124 def delete(key) if @store.has_key?(key) item = @store.delete(key) @strategy.delete(item) item.value else nil end end |
#fetch(key, default_value = nil) ⇒ Object Also known as: []
134 135 136 137 138 139 140 141 142 143 |
# File 'lib/cache/cache.rb', line 134 def fetch(key, default_value=nil) if @store.has_key?(key) item = @store.fetch(key) @strategy.access(item) @store.store(key, item) if @store_on_update item.value else default_value end end |
#has_key?(key) ⇒ Boolean
120 121 122 |
# File 'lib/cache/cache.rb', line 120 def has_key?(key) @store.has_key?(key) end |
#store(key, value) ⇒ Object Also known as: []=
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/cache/cache.rb', line 145 def store(key, value) if @store.has_key?(key) # update only item = @store.fetch(key) item.value = value @strategy.access(item) @store.store(key, item) if @store_on_update else # insert new item item = @strategy.item_class.new item.value = value @strategy.insert_or_extrude(item, @store) do |k, i| @strategy.delete(i) @store.delete(k) end @store.store(key, item) # correct! end value end |