class DeviceDetector::MemoryCache
Constants
- DEFAULT_MAX_KEYS
Attributes
data[R]
lock[R]
max_keys[R]
Public Class Methods
new(config)
click to toggle source
# File lib/device_detector/memory_cache.rb, line 9 def initialize(config) @data = {} @max_keys = config[:max_cache_keys] || DEFAULT_MAX_KEYS @lock = Mutex.new end
Public Instance Methods
get(key)
click to toggle source
# File lib/device_detector/memory_cache.rb, line 22 def get(key) data[String(key)] end
get_or_set(key, value = nil) { || ... }
click to toggle source
# File lib/device_detector/memory_cache.rb, line 30 def get_or_set(key, value = nil) string_key = String(key) if key?(string_key) get(string_key) else value = yield if block_given? set(string_key, value) end end
key?(string_key)
click to toggle source
# File lib/device_detector/memory_cache.rb, line 26 def key?(string_key) data.key?(string_key) end
set(key, value)
click to toggle source
# File lib/device_detector/memory_cache.rb, line 15 def set(key, value) lock.synchronize do purge_cache data[String(key)] = value end end
Private Instance Methods
purge_cache()
click to toggle source
# File lib/device_detector/memory_cache.rb, line 43 def purge_cache key_size = data.size if key_size >= max_keys # always remove about 1/3 of keys to reduce garbage collecting amount_of_keys = key_size / 3 data.keys.first(amount_of_keys).each { |key| data.delete(key) } end end