1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
# frozen_string_literal: true
module Sprockets
class Cache
# 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
#
class MemoryStore
# Internal: Default key limit for store.
DEFAULT_MAX_SIZE = 1000
# Public: Initialize the cache store.
#
# max_size - A Integer of the maximum number of keys the store will hold.
# (default: 1000).
def initialize(max_size = DEFAULT_MAX_SIZE)
@max_size = max_size
@cache = {}
@mutex = Mutex.new
end
# 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.
def get(key)
@mutex.synchronize do
exists = true
value = @cache.delete(key) { exists = false }
if exists
@cache[key] = value
else
nil
end
end
end
# 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.
def set(key, value)
@mutex.synchronize do
@cache.delete(key)
@cache[key] = value
@cache.shift if @cache.size > @max_size
end
value
end
# Public: Pretty inspect
#
# Returns String.
def inspect
@mutex.synchronize do
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
end
end
# Public: Clear the cache
#
# Returns true
def clear(options=nil)
@mutex.synchronize do
@cache.clear
end
true
end
end
end
end
|