Module: Garner::Cache

Defined in:
lib/garner/cache.rb,
lib/garner/cache/binding.rb,
lib/garner/cache/context.rb,
lib/garner/cache/identity.rb

Defined Under Namespace

Modules: Binding, Context Classes: Identity, NilBinding

Class Method Summary collapse

Class Method Details

.compound_key(bindings, key_hash) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/garner/cache.rb', line 23

def self.compound_key(bindings, key_hash)
  binding_keys = bindings.map { |binding| key_for(binding) }.compact
  if binding_keys.size == bindings.size
    # All bindings have non-nil cache keys, proceed.
    {
      binding_keys: binding_keys,
      context_keys: key_hash
    }
  else
    # A nil cache key was generated. Skip caching.
    # TODO: Replace this ill-documented "nil to skip" behavior
    # with exceptions on inability to generate a cache key.
    nil
  end
end

.fetch(bindings, key_hash, options_hash, &_block) ⇒ Object

Fetch a result from cache.

Parameters:

  • bindings (Array)

    Objects to which the the cache result should be bound. These objects’ keys are injected into the compound cache key.

  • key_hash (Hash)

    Hash to comprise the compound cache key.

  • options_hash (Hash)

    Options to be passed to Garner.config.cache.



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

def self.fetch(bindings, key_hash, options_hash, &_block)
  if (compound_key = compound_key(bindings, key_hash))
    result = Garner.config.cache.fetch(compound_key, options_hash) do
      yield
    end
    Garner.config.cache.delete(compound_key, options_hash) unless result
  else
    result = yield
  end
  result
end

.key_for(binding) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/garner/cache.rb', line 39

def self.key_for(binding)
  if binding.nil?
    return nil unless Garner.config.whiny_nils?
    fail NilBinding
  else
    binding.garner_cache_key
  end
end