class Chef::EncryptedAttribute::CacheLru

Implements an LRU (Least Recently Used) cache object.

The LRU cache algorithm discards the least recently used items first.

This class extends from Hash class and adds methods to behave as a cache.

You can use the `clear` class method to clean a cache:

“`ruby Chef::EncryptedAttribute::RemoteClients.cache.clear Chef::EncryptedAttribute::RemoteNodes.cache.clear Chef::EncryptedAttribute::RemoteUsers.cache.clear Chef::EncryptedAttribute::RemoteNode.cache.clear “`

@note Based on [SamSaffron](github.com/SamSaffron) work:

https://github.com/SamSaffron/lru_redux

@see API

Public Class Methods

new(size = nil) click to toggle source

Constructs a new Cache LRU object.

@param size [Fixnum] Cache maximum size in object count.

Calls superclass method
# File lib/chef/encrypted_attribute/cache_lru.rb, line 49
def initialize(size = nil)
  super
  max_size(size)
end

Public Instance Methods

[](key) click to toggle source

Reads a cache key.

@param key [String, Symbol] cache key to read. @return [Mixed] cache key value.

Calls superclass method
# File lib/chef/encrypted_attribute/cache_lru.rb, line 77
def [](key)
  return nil unless key?(key)
  val = super(key)
  self[key] = val
end
[]=(key, val) click to toggle source

Sets a cache key.

Some keys will be removed if the cache size grows too much. The keys to be removed will be chosen using the LRU algorithm.

@param key [String, Symbol] cache key to set. @param val [Mixed] cache key value. @return [Mixed] cache key value.

Calls superclass method
# File lib/chef/encrypted_attribute/cache_lru.rb, line 91
def []=(key, val)
  if max_size > 0 # unnecessary "if", small optimization?
    delete(key)
    super(key, val)
    pop_tail
  end
  val
end
max_size(arg = nil) click to toggle source

Reads or sets the cache maximum size.

Removes some values if needed (when the size is reduced).

The cache size is `1024` by default.

@param arg [Fixnum] cache maximum size to set. @return [Fixnum] cache maximum size.

# File lib/chef/encrypted_attribute/cache_lru.rb, line 62
def max_size(arg = nil)
  set_or_return(
    :max_size,
    arg,
    kind_of: [Fixnum], default: 1024,
    callbacks: { 'should not be lower that zero' => ->(x) { x >= 0 } }
  )
  pop_tail unless arg.nil?
  @max_size
end

Protected Instance Methods

pop_tail() click to toggle source

Removes the tail elements until the size is correct.

This method is needed to implement the LRU algorithm.

@return void

# File lib/chef/encrypted_attribute/cache_lru.rb, line 107
def pop_tail
  delete(first[0]) while size > max_size
end