Class: SimpleCache::MemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_cache.rb

Overview

TODO: add a super-class and implement FileSystemCache

Instance Attribute Summary collapse

Instance Method Summary collapse

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(options = {})
    @cache = {}
    @cache_size = 0
    @key_access = {}
    @max_size = options[:max_size] || 32 * 1024 #32 megabytes
    @timeout  = options[:timeout]  || 60*30 #30 minutes
end

Instance Attribute Details

#cache_sizeObject (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

Returns:

  • (Boolean)


71
72
73
# File 'lib/simple_cache.rb', line 71

def has_key?(key)
    !!@cache[encode(key)]
end

#pruneObject



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

Returns:

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