Class: TRuby::MemoryCache
- Inherits:
-
Object
- Object
- TRuby::MemoryCache
- Defined in:
- lib/t_ruby/cache.rb
Overview
In-memory LRU cache
Instance Attribute Summary collapse
-
#hits ⇒ Object
readonly
Returns the value of attribute hits.
-
#max_size ⇒ Object
readonly
Returns the value of attribute max_size.
-
#misses ⇒ Object
readonly
Returns the value of attribute misses.
Instance Method Summary collapse
- #clear ⇒ Object
- #delete(key) ⇒ Object
- #get(key) ⇒ Object
- #hit_rate ⇒ Object
-
#initialize(max_size: 1000) ⇒ MemoryCache
constructor
A new instance of MemoryCache.
- #set(key, value) ⇒ Object
- #size ⇒ Object
- #stats ⇒ Object
Constructor Details
#initialize(max_size: 1000) ⇒ MemoryCache
Returns a new instance of MemoryCache.
44 45 46 47 48 49 50 51 |
# File 'lib/t_ruby/cache.rb', line 44 def initialize(max_size: 1000) @max_size = max_size @cache = {} @access_order = [] @hits = 0 @misses = 0 @mutex = Mutex.new end |
Instance Attribute Details
#hits ⇒ Object (readonly)
Returns the value of attribute hits.
42 43 44 |
# File 'lib/t_ruby/cache.rb', line 42 def hits @hits end |
#max_size ⇒ Object (readonly)
Returns the value of attribute max_size.
42 43 44 |
# File 'lib/t_ruby/cache.rb', line 42 def max_size @max_size end |
#misses ⇒ Object (readonly)
Returns the value of attribute misses.
42 43 44 |
# File 'lib/t_ruby/cache.rb', line 42 def misses @misses end |
Instance Method Details
#clear ⇒ Object
83 84 85 86 87 88 89 90 |
# File 'lib/t_ruby/cache.rb', line 83 def clear @mutex.synchronize do @cache.clear @access_order.clear @hits = 0 @misses = 0 end end |
#delete(key) ⇒ Object
76 77 78 79 80 81 |
# File 'lib/t_ruby/cache.rb', line 76 def delete(key) @mutex.synchronize do @cache.delete(key) @access_order.delete(key) end end |
#get(key) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/t_ruby/cache.rb', line 53 def get(key) @mutex.synchronize do if @cache.key?(key) @hits += 1 touch(key) @cache[key].access else @misses += 1 nil end end end |
#hit_rate ⇒ Object
96 97 98 99 100 101 |
# File 'lib/t_ruby/cache.rb', line 96 def hit_rate total = @hits + @misses return 0.0 if total.zero? @hits.to_f / total end |
#set(key, value) ⇒ Object
66 67 68 69 70 71 72 73 74 |
# File 'lib/t_ruby/cache.rb', line 66 def set(key, value) @mutex.synchronize do evict if @cache.size >= @max_size && !@cache.key?(key) @cache[key] = CacheEntry.new(key, value) touch(key) value end end |
#size ⇒ Object
92 93 94 |
# File 'lib/t_ruby/cache.rb', line 92 def size @cache.size end |
#stats ⇒ Object
103 104 105 106 107 108 109 110 111 |
# File 'lib/t_ruby/cache.rb', line 103 def stats { size: size, max_size: @max_size, hits: @hits, misses: @misses, hit_rate: hit_rate, } end |