cached_proc

A simple child class of Proc to cache the result for a period of time.


License
BSD-1-Clause
Install
gem install cached_proc -v 0.0.1

Documentation

Gem Version Dependency Status

Master branch: Build Status Coveralls Status Code Climate

Staging branch: Build Status Coveralls Status

Build State

This project uses continuous integration to help ensure that a quality product is delivered. Travis CI monitors two branches (versions) of the code - Master (which is what gets released) and Staging (which is what is currently being developed ready for moving to master).

Ruby Versions

This gem supports the following versions of ruby, it may work on other versions but is not tested against them so don't rely on it.

  • 2.3.0
  • 2.3.1
  • 2.4.0

Cachd

A collection of objects which cache their values.

Cachd::Proc

This takes a ttl and a proc. Everytime the proc is called it will check if an internal Hash contains a value for the args which have been passed to the proc. If a value is found and is within time it is returned otherwise the proc is called, the result cached and finally the result is returned.

require 'cachd'

# Simply return the number of times the code inside the proc has run.
cached_proc = Cachd::Proc.new(5) do |str|
  @counts ||= Hash.new(0)
  @counts[str] += 1
  "Called #{@counts[str]} times with #{str}"
end

cached_proc.call('a') # returns "Called 1 times with a"
cached_proc.call('a') # returns "Called 1 times with a"
cached_proc.call('b') # returns "Called 1 times with b"
cached_proc.call('b') # returns "Called 1 times with b"

sleep 10
cached_proc.call('a') # returns "Called 2 times with a"
cached_proc.call('b') # returns "Called 2 times with b"

Cachd::Hash

This behaves just like a Hash except each value has a TTL (time to live) and becomes unretrievable after that time.

require 'cachd'

cached_hash = Cachd::Hash.new(10)
cached_hash[:a] = 'a'
cached_hash.proc_for(:b) do |_hash, key|
  @counts ||= Hash.new(0)
  @counts[key] += 1
  "Called #{@counts[key]} times with #{key}"
end

cached_hash[:a] # returns "a"
cached_hash[:b] # returns "Called 1 times with b"
cached_hash[:b] # returns "Called 1 times with b"

sleep 10
cached_hash[:a] # returns nil
cached_hash[:b] # returns "Called 2 times with b"

Installation

Add to your Gemfile and run the bundle command to install it.

gem 'cachd', '~> 0.0'

Documentation & Versioning

Documentation can be found on rubydoc.info

We follow the Semantic Versioning concept,