Class: Astronoby::Cache

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/astronoby/cache.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

DEFAULT_MAX_SIZE =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ void

Parameters:

  • max_size (Integer) (defaults to: DEFAULT_MAX_SIZE)

    Maximum number of entries allowed in the cache



18
19
20
21
22
23
24
# File 'lib/astronoby/cache.rb', line 18

def initialize(max_size = DEFAULT_MAX_SIZE)
  @max_size = max_size
  @hash = {}
  @head = nil
  @tail = nil
  @mutex = Monitor.new
end

Instance Attribute Details

#max_sizeObject

Returns the value of attribute max_size.



14
15
16
# File 'lib/astronoby/cache.rb', line 14

def max_size
  @max_size
end

Instance Method Details

#[](key) ⇒ Object?

Returns the value, or nil if not found.

Parameters:

  • key (Object)

    the cache key

Returns:

  • (Object, nil)

    the value, or nil if not found



28
29
30
31
32
33
34
35
36
# File 'lib/astronoby/cache.rb', line 28

def [](key)
  @mutex.synchronize do
    entry = @hash[key]
    if entry
      move_to_head(entry)
      entry.value
    end
  end
end

#[]=(key, value) ⇒ Object

Returns the value set.

Parameters:

  • key (Object)
  • value (Object)

Returns:

  • (Object)

    the value set



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/astronoby/cache.rb', line 41

def []=(key, value)
  @mutex.synchronize do
    entry = @hash[key]
    if entry
      entry.value = value
      move_to_head(entry)
    else
      entry = Entry.new(key, value)
      add_to_head(entry)
      @hash[key] = entry
      evict_last_recently_used if @hash.size > @max_size
    end
  end
end

#clearvoid

This method returns an undefined value.



72
73
74
75
76
77
# File 'lib/astronoby/cache.rb', line 72

def clear
  @mutex.synchronize do
    @hash.clear
    @head = @tail = nil
  end
end

#fetch(key) ⇒ Object

Returns Cached or computed value.

Parameters:

  • key (Object)

Yield Returns:

  • (Object)

    Value to store if key is missing.

Returns:

  • (Object)

    Cached or computed value.



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/astronoby/cache.rb', line 59

def fetch(key)
  return self[key] if @mutex.synchronize { @hash.key?(key) }

  value = yield

  @mutex.synchronize do
    self[key] = value unless @hash.key?(key)
  end

  value
end

#sizeInteger

Returns:

  • (Integer)


80
81
82
# File 'lib/astronoby/cache.rb', line 80

def size
  @mutex.synchronize { @hash.size }
end