Class: AmplitudeExperiment::LRUCache
- Inherits:
-
Object
- Object
- AmplitudeExperiment::LRUCache
- Defined in:
- lib/experiment/util/lru_cache.rb
Overview
Cache
Instance Method Summary collapse
- #clear ⇒ Object
- #get(key) ⇒ Object
-
#initialize(capacity, ttl_millis) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #put(key, value) ⇒ Object
- #remove(key) ⇒ Object
Constructor Details
#initialize(capacity, ttl_millis) ⇒ LRUCache
Returns a new instance of LRUCache.
26 27 28 29 30 31 32 |
# File 'lib/experiment/util/lru_cache.rb', line 26 def initialize(capacity, ttl_millis) @capacity = capacity @ttl_millis = ttl_millis @cache = {} @head = nil @tail = nil end |
Instance Method Details
#clear ⇒ Object
67 68 69 70 71 |
# File 'lib/experiment/util/lru_cache.rb', line 67 def clear @cache.clear @head = nil @tail = nil end |
#get(key) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/experiment/util/lru_cache.rb', line 47 def get(key) node = @cache[key] return nil unless node time_elapsed = (Time.now.to_f * 1000).to_i - node.data.created_at if time_elapsed > @ttl_millis remove(key) return nil end remove_from_list(key) insert_to_list(node) node.data.value end |
#put(key, value) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/experiment/util/lru_cache.rb', line 34 def put(key, value) if @cache.key?(key) remove_from_list(key) elsif @cache.size >= @capacity evict_lru end cache_item = CacheItem.new(key, value) node = ListNode.new(cache_item) @cache[key] = node insert_to_list(node) end |
#remove(key) ⇒ Object
62 63 64 65 |
# File 'lib/experiment/util/lru_cache.rb', line 62 def remove(key) remove_from_list(key) @cache.delete(key) end |