Class: Cache::StorageCache

Inherits:
Cache show all
Defined in:
lib/cache/cache.rb

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

Wee::Utils::LRUCache

Instance Method Summary collapse

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

Returns:

  • (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