Class: ESI::RubyCache

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

Overview

A ruby thread safe cache, stores cached fragments in the current ruby process memory

A hash table indexed by cache_key of Fragments. the cache is made thread safe if the external invalidator is active otherwise the Mutex is a no op

Default cache.

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RubyCache

Returns a new instance of RubyCache.



167
168
169
170
171
# File 'lib/esi/cache.rb', line 167

def initialize( options = {} )
  super()
  @semaphore = Mutex.new
  @cache = {}
end

Instance Method Details

#cached?(uri, params) ⇒ Boolean

Returns:

  • (Boolean)


173
174
175
176
177
# File 'lib/esi/cache.rb', line 173

def cached?( uri, params )
  key = cache_key(uri,params)
  fragment = @semaphore.synchronize { @cache[key] }
  fragment and fragment.valid?
end

#delete(key) ⇒ Object



206
207
208
# File 'lib/esi/cache.rb', line 206

def delete( key )
  @semaphore.synchronize { @cache.delete(key) }
end

#delete_unlocked(key) ⇒ Object



210
211
212
# File 'lib/esi/cache.rb', line 210

def delete_unlocked( key )
  @cache.delete(key)
end

#get(uri, params) ⇒ Object



179
180
181
182
183
# File 'lib/esi/cache.rb', line 179

def get( uri, params )
  key = cache_key(uri,params)
  fragment = @semaphore.synchronize { @cache[key] }
  fragment.dup if fragment and fragment.valid? and fragment.respond_to?(:dup)
end

#keys(&block) ⇒ Object



198
199
200
201
202
203
204
# File 'lib/esi/cache.rb', line 198

def keys(&block)
  @semaphore.synchronize do
    @cache.each do|key,data|
      yield key, data
    end
  end
end

#put(uri, params, max_age, body) ⇒ Object



185
186
187
188
189
190
191
# File 'lib/esi/cache.rb', line 185

def put( uri, params, max_age, body )
  key = cache_key(uri,params)
  @semaphore.synchronize do
    @cache[key] = Fragment.new(uri,max_age,body)
    sweep_unlocked!
  end
end

#sweep!Object

run through the cache and dump anything that has expired



194
195
196
# File 'lib/esi/cache.rb', line 194

def sweep!
  @semaphore.synchronize { sweep_unlocked! }
end

#sweep_unlocked!Object



214
215
216
# File 'lib/esi/cache.rb', line 214

def sweep_unlocked!
  @cache.reject! {|k,v| !v.valid? }
end