Class: Condenser::Cache::MemoryStore

Inherits:
Condenser::CacheStore show all
Defined in:
lib/condenser/cache/memory_store.rb

Overview

Public: Basic in memory LRU cache.

Assign the instance to the Environment#cache.

environment.cache = Sprockets::Cache::MemoryStore.new(1000)

See Also

ActiveSupport::Cache::MemoryStore

Constant Summary collapse

DEFAULT_MAX_SIZE =

Internal: Default key limit for store.

33_554_432
PER_ENTRY_OVERHEAD =

32 Megabytes

240

Instance Method Summary collapse

Methods inherited from Condenser::CacheStore

#delete, #fetch, #fetch_if

Constructor Details

#initialize(options = {}) ⇒ MemoryStore

Returns a new instance of MemoryStore.



18
19
20
21
22
23
# File 'lib/condenser/cache/memory_store.rb', line 18

def initialize(options = {})
  @max_size = options[:size] || DEFAULT_MAX_SIZE
  @cache = {}
  @key_access = {}
  @cache_size = 0
end

Instance Method Details

#cached_size(key, value) ⇒ Object



37
38
39
# File 'lib/condenser/cache/memory_store.rb', line 37

def cached_size(key, value)
  key.to_s.bytesize + value.bytesize + PER_ENTRY_OVERHEAD
end

#clearObject



25
26
27
28
29
# File 'lib/condenser/cache/memory_store.rb', line 25

def clear
  @cache.clear
  @key_access.clear
  @cache_size = 0
end

#get(key) ⇒ Object



31
32
33
34
35
# File 'lib/condenser/cache/memory_store.rb', line 31

def get(key)
  value = @cache[key]
  @key_access[key] = Time.now.to_f if value
  value
end

#inspectObject

Public: Pretty inspect

Returns String.



64
65
66
# File 'lib/condenser/cache/memory_store.rb', line 64

def inspect
  "#<#{self.class} size=#{@cache_size}/#{@max_size}>"
end

#pruneObject



53
54
55
56
57
58
59
# File 'lib/condenser/cache/memory_store.rb', line 53

def prune
  keys = @key_access.keys.sort { |a, b| @key_access[a].to_f <=> @key_access[b].to_f }
  keys.each do |key|
    delete(key)
    return if @cache_size <= @max_size
  end
end

#set(key, value) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/condenser/cache/memory_store.rb', line 41

def set(key, value)
  if old_value = @cache[key]
    @cache_size -= (old_value.bytesize - value.bytesize)
  else
    @cache_size += cached_size(key, value)
  end
  @cache[key] = value
  @key_access[key] = Time.now.to_f
  prune if @cache_size > @max_size
  value
end