Class: HashCache

Inherits:
Hash show all
Defined in:
lib/hashcache.rb

Overview

A very simple cache. Works just like a Hash, but can optionally store values during the fetch process.

Example:

hc = HashCache.new
hc.fetch("foo")
=> nil
hc.fetch("foo"){:bar} # Block gets called because 'foo' is nil
=> :bar
hc.fetch("foo"){raise "Block won't be called because 'foo' is cached"}
=> :bar

Instance Method Summary collapse

Methods included from InactiveSupport::CoreExtensions::Hash::Keys

#assert_valid_keys, #stringify_keys, #stringify_keys!, #symbolize_keys, #symbolize_keys!

Instance Method Details

#fetch(key, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/hashcache.rb', line 13

def fetch(key, &block)
  if has_key?(key) 
    self[key] 
  elsif block
    self[key] = block.call
  else
    nil
  end
end