Class: Luoma::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/luoma/cache.rb,
sig/luoma/cache.rbs

Overview

A least recently used cache relying on Ruby hash insertion order.

Direct Known Subclasses

ThreadSafeLRUCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = 128) ⇒ LRUCache

Returns a new instance of LRUCache.

Parameters:

  • max_size (::Integer) (defaults to: 128)


10
11
12
13
# File 'lib/luoma/cache.rb', line 10

def initialize(max_size = 128)
  @data = {}
  @max_size = max_size
end

Instance Attribute Details

#max_sizeInteger (readonly)

Returns the value of attribute max_size.

Returns:

  • (Integer)


8
9
10
# File 'lib/luoma/cache.rb', line 8

def max_size
  @max_size
end

Instance Method Details

#[](key) ⇒ nil, untyped

Return the cached value or nil if key does not exist.

Parameters:

  • key (Object)

Returns:

  • (nil, untyped)


16
17
18
19
20
21
22
23
# File 'lib/luoma/cache.rb', line 16

def [](key)
  val = @data[key]
  return nil if val.nil?

  @data.delete(key)
  @data[key] = val
  val
end

#[]=(key, value) ⇒ Object

Parameters:

  • key (Object)
  • value (Object)

Returns:

  • (Object)


25
26
27
28
29
30
31
32
# File 'lib/luoma/cache.rb', line 25

def []=(key, value)
  if @data.key?(key)
    @data.delete(key)
  elsif @data.length >= @max_size
    @data.delete((@data.first || raise)[0])
  end
  @data[key] = value
end

#keysArray[untyped]

Returns:

  • (Array[untyped])


38
39
40
# File 'lib/luoma/cache.rb', line 38

def keys
  @data.keys
end

#lengthInteger

Returns:

  • (Integer)


34
35
36
# File 'lib/luoma/cache.rb', line 34

def length
  @data.length
end