Class: Chef::EncryptedAttribute::CacheLru

Inherits:
Hash
  • Object
show all
Includes:
Mixin::ParamsValidate
Defined in:
lib/chef/encrypted_attribute/cache_lru.rb

Overview

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:

Chef::EncryptedAttribute::RemoteClients.cache.clear
Chef::EncryptedAttribute::RemoteNodes.cache.clear
Chef::EncryptedAttribute::RemoteUsers.cache.clear
Chef::EncryptedAttribute::RemoteNode.cache.clear

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(size = nil) ⇒ CacheLru

Constructs a new Cache LRU object.

Parameters:

  • size (Fixnum) (defaults to: nil)

    Cache maximum size in object count.



49
50
51
52
# File 'lib/chef/encrypted_attribute/cache_lru.rb', line 49

def initialize(size = nil)
  super
  max_size(size)
end

Instance Method Details

#[](key) ⇒ Mixed

Reads a cache key.

Parameters:

  • key (String, Symbol)

    cache key to read.

Returns:

  • (Mixed)

    cache key value.



77
78
79
80
81
# 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) ⇒ Mixed

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.

Parameters:

  • key (String, Symbol)

    cache key to set.

  • val (Mixed)

    cache key value.

Returns:

  • (Mixed)

    cache key value.



91
92
93
94
95
96
97
98
# 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) ⇒ Fixnum

Reads or sets the cache maximum size.

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

The cache size is 1024 by default.

Parameters:

  • arg (Fixnum) (defaults to: nil)

    cache maximum size to set.

Returns:

  • (Fixnum)

    cache maximum size.



62
63
64
65
66
67
68
69
70
71
# 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