Class: CountedCache
- Inherits:
-
Object
- Object
- CountedCache
- Defined in:
- lib/counted_cache.rb,
lib/counted_cache/version.rb
Constant Summary collapse
- VERSION =
"0.2.0".freeze
- DESCRIPTION =
"counted_cache: A cache for mostly read data with a high cost of retrieval.".freeze
Instance Attribute Summary collapse
-
#depth ⇒ Object
How many data elements should be retained?.
-
#hits ⇒ Object
readonly
How many times was data found in the cache?.
-
#misses ⇒ Object
readonly
How many times was data not in the cache?.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Get a data item.
-
#free ⇒ Object
How many cache slots are free?.
-
#initialize(depth = 10, &load_block) ⇒ CountedCache
constructor
Setup the cache.
-
#set_save_block(&save_block) ⇒ Object
Set up the optional block called to save data.
Constructor Details
#initialize(depth = 10, &load_block) ⇒ CountedCache
Setup the cache
20 21 22 23 24 25 26 27 28 29 30 |
# 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 |
Instance Attribute Details
#depth ⇒ Object
How many data elements should be retained?
11 12 13 |
# File 'lib/counted_cache.rb', line 11 def depth @depth end |
#hits ⇒ Object (readonly)
How many times was data found in the cache?
14 15 16 |
# File 'lib/counted_cache.rb', line 14 def hits @hits end |
#misses ⇒ Object (readonly)
How many times was data not in the cache?
17 18 19 |
# File 'lib/counted_cache.rb', line 17 def misses @misses end |
Instance Method Details
#[](key) ⇒ Object
Get a data item.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# 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 |
#free ⇒ Object
How many cache slots are free?
62 63 64 |
# File 'lib/counted_cache.rb', line 62 def free @depth - @data_space.length end |
#set_save_block(&save_block) ⇒ Object
Set up the optional block called to save data.
33 34 35 |
# File 'lib/counted_cache.rb', line 33 def set_save_block(&save_block) @save_block = save_block end |