Class: Sprockets::Cache::MemoryStore

Inherits:
Object
  • Object
show all
Defined in:
lib/sprockets/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.

1000

Instance Method Summary collapse

Constructor Details

#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ MemoryStore

Public: Initialize the cache store.

max_size - A Integer of the maximum number of keys the store will hold.

(default: 1000).


22
23
24
25
# File 'lib/sprockets/cache/memory_store.rb', line 22

def initialize(max_size = DEFAULT_MAX_SIZE)
  @max_size = max_size
  @cache = {}
end

Instance Method Details

#clear(options = nil) ⇒ Object

Public: Clear the cache

Returns true



69
70
71
72
# File 'lib/sprockets/cache/memory_store.rb', line 69

def clear(options=nil)
  @cache.clear
  true
end

#get(key) ⇒ Object

Public: Retrieve value from cache.

This API should not be used directly, but via the Cache wrapper API.

key - String cache key.

Returns Object or nil or the value is not set.



34
35
36
37
38
39
40
41
42
# File 'lib/sprockets/cache/memory_store.rb', line 34

def get(key)
  exists = true
  value = @cache.delete(key) { exists = false }
  if exists
    @cache[key] = value
  else
    nil
  end
end

#inspectObject

Public: Pretty inspect

Returns String.



62
63
64
# File 'lib/sprockets/cache/memory_store.rb', line 62

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

#set(key, value) ⇒ Object

Public: Set a key and value in the cache.

This API should not be used directly, but via the Cache wrapper API.

key - String cache key. value - Object value.

Returns Object value.



52
53
54
55
56
57
# File 'lib/sprockets/cache/memory_store.rb', line 52

def set(key, value)
  @cache.delete(key)
  @cache[key] = value
  @cache.shift if @cache.size > @max_size
  value
end