Class: CaRuby::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/caruby/database/cache.rb

Overview

Cache for objects held in memory and accessed by key.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|item| ... } ⇒ Cache

Returns a new instance of Cache.

Yields:

  • (item)

    returns the key for the given item to cache

Yield Parameters:

  • item

    the object to cache



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/caruby/database/cache.rb', line 12

def initialize
  # Make the class => {key => item} hash.
  # The {key => item} hash takes an item as an argument and converts
  # it to the key by calling the block given to this initializer.
  @ckh = Jinx::LazyHash.new do
    Jinx::KeyTransformerHash.new do |obj|
      yield(obj) or Jinx.fail(ArgumentError, "The object to cache does not have a key: #{obj}")
    end
  end
  @sticky = Set.new
end

Instance Attribute Details

#stickyObject (readonly)

The classes which are not cleared when #clear is called without the all flag.



8
9
10
# File 'lib/caruby/database/cache.rb', line 8

def sticky
  @sticky
end

Instance Method Details

#[](item) ⇒ Object

If there is already a cached object with the same key as the given item, then this method returns that cached object. Otherwise, this method caches the given item and returns that item.

Parameters:

  • item

    the object to resolve

Returns:

  • the object cached with the same class and key as the given item

Raises:

  • (ArgumentError)

    if the item does not have a key



31
32
33
# File 'lib/caruby/database/cache.rb', line 31

def [](item)
  @ckh[item.class][item]
end

#add(item) ⇒ Object

Adds the given item to this cache, unless one already exists.

Parameters:

  • item

    the object to cache

Returns:

  • the cached item



39
40
41
# File 'lib/caruby/database/cache.rb', line 39

def add(item)
  @ckh[item.class][item] ||= item
end

#add!(item) ⇒ Object

Adds the given item to this cache. Overwrites an existing cache entry for the given item’s key, if one already exists.

Parameters:

  • item

    the object to cache



47
48
49
# File 'lib/caruby/database/cache.rb', line 47

def add!(item)
  @ckh[item.class][item] = item
end

#clearObject

Clears the non-sticky class caches.



52
53
54
55
56
57
58
# File 'lib/caruby/database/cache.rb', line 52

def clear
  if @sticky.empty? then
    @ckh.clear
  else
    @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) }
  end
end