class CountedCache

Constants

DESCRIPTION
VERSION

Attributes

depth[R]

How many data elements should be retained?

hits[R]

How many times was data found in the cache?

misses[R]

How many times was data not in the cache?

Public Class Methods

new(depth = 10, &load_block) click to toggle source

Setup the cache

# File lib/counted_cache.rb, line 20
def initialize(depth = 10, &load_block)
  fail "A data loading block is required" unless block_given?

  @load_block = load_block
  @save_block = Proc.new {}
  @key_space  = Hash.new {|hash, key| hash[key] = CountedCacheItem.new(key)}
  @data_space = Array.new
  self.depth  = depth
  @hits       = 0
  @misses     = 0
end

Public Instance Methods

[](key) click to toggle source

Get a data item.

# File lib/counted_cache.rb, line 38
def [](key)
  item = @key_space[key]

  if item.empty?
    item.data = @load_block.call(key)
    adjust_cache(1)
    @data_space << item
    @misses += 1
  else
    @hits += 1
  end

  item.data
end
depth=(value) click to toggle source

Set the new depth.

# File lib/counted_cache.rb, line 54
def depth=(value)
  value = value.to_i
  fail "The depth must be greater than zero." if value < 1
  @depth = value
  adjust_cache(0)
end
free() click to toggle source

How many cache slots are free?

# File lib/counted_cache.rb, line 62
def free
  @depth - @data_space.length
end
set_save_block(&save_block) click to toggle source

Set up the optional block called to save data.

# File lib/counted_cache.rb, line 33
def set_save_block(&save_block)
  @save_block = save_block
end

Private Instance Methods

adjust_cache(reserve) click to toggle source

Make sure the data space has at least one free slot.

# File lib/counted_cache.rb, line 69
def adjust_cache(reserve)
  return if free >= reserve

  @data_space.sort_by!(&:count)

  while free != reserve
    @data_space.shift.purge(@save_block)
  end
end