Class: RightScale::CertificateCache

Inherits:
Object
  • Object
show all
Defined in:
lib/right_agent/security/certificate_cache.rb

Overview

Implements a simple LRU cache: items that are the least accessed are deleted first.

Constant Summary collapse

DEFAULT_CACHE_MAX_COUNT =

Max number of items to keep in memory

100

Instance Method Summary collapse

Constructor Details

#initialize(max_count = DEFAULT_CACHE_MAX_COUNT) ⇒ CertificateCache

Initialize cache



33
34
35
36
37
# File 'lib/right_agent/security/certificate_cache.rb', line 33

def initialize(max_count = DEFAULT_CACHE_MAX_COUNT)
  @items = {}
  @list = []
  @max_count = max_count
end

Instance Method Details

#delete(key) ⇒ Object

Delete item from cache



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/right_agent/security/certificate_cache.rb', line 73

def delete(key)
  c = @items[key]
  if c
    @items.delete(key)
    @list.each_index do |i|
     if @list[i] == key
       @list.delete_at(i)
       break
     end
    end
    c
  end
end

#get(key) ⇒ Object Also known as: []

Retrieve item from cache Store item returned by given block if any



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/right_agent/security/certificate_cache.rb', line 55

def get(key)
  if @items.include?(key)
    @list.each_index do |i|
      if @list[i] == key
        @list.delete_at(i)
        break
      end
    end
    @list.push(key)
    @items[key]
  else
    return nil unless block_given?
     self[key] = yield
  end
end

#put(key, item) ⇒ Object Also known as: []=

Add item to cache



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/right_agent/security/certificate_cache.rb', line 40

def put(key, item)
  if @items.include?(key)
    delete(key)
  end
  if @list.size == @max_count
    delete(@list.first)
  end
  @items[key] = item
  @list.push(key)
  item
end