Class: BoundedLruCache

Inherits:
Object show all
Defined in:
lib/rpdf2txt-rockit/bounded_lru_cache.rb

Overview

Cache as hash with bounded size. Will delete least recently used (LRU) entry if full when new key-value pair added. NOTE: Not thread safeā€¦

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = 2**30-1, anObject = nil) ⇒ BoundedLruCache

Returns a new instance of BoundedLruCache.



7
8
9
# File 'lib/rpdf2txt-rockit/bounded_lru_cache.rb', line 7

def initialize(max_size = 2**30-1, anObject = nil)
  @hash, @uses, @max_size = Hash.new(anObject), Array.new, max_size
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(methodId, *args) ⇒ Object

Delegate undefined methods to the hash



24
25
26
27
28
29
30
# File 'lib/rpdf2txt-rockit/bounded_lru_cache.rb', line 24

def method_missing(methodId, *args)
  if @hash.respond_to?(methodId)
    @hash.send(methodId, *args)
  else
    super
  end
end

Instance Attribute Details

#max_sizeObject

Returns the value of attribute max_size.



5
6
7
# File 'lib/rpdf2txt-rockit/bounded_lru_cache.rb', line 5

def max_size
  @max_size
end

Instance Method Details

#[](key) ⇒ Object



17
18
19
20
21
# File 'lib/rpdf2txt-rockit/bounded_lru_cache.rb', line 17

def [](key)
  res = @hash[key] 
  latest_used_key(key) if res
  res
end

#[]=(key, val) ⇒ Object



11
12
13
14
15
# File 'lib/rpdf2txt-rockit/bounded_lru_cache.rb', line 11

def []=(key, val)
  delete_least_recently_used if @hash.length >= @max_size
  latest_used_key(key)
  @hash[key] = val
end