Implements a key-based cache with LRU or TTL policy
Ruby
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.ruby-gemset
.ruby-version
Gemfile
Gemfile.lock
LICENSE
README
Rakefile
volatile_hash.gemspec

README

Implements a Time-to-live based cache and a Least-recently-used cache.

= Usage

cache = VolatileHash.new(:strategy => 'ttl', :ttl => 3600)
#  TTL-based, default TTL is 3600 seconds. The value will be cached no longer
#  than 3600 seconds after it is inserted into the cache.

cache = VolatileHash.new(:strategy => 'ttl', :ttl => 3600, :refresh => true)
#  TTL-based, default TTL is 3600 seconds. The value will be cached no longer
#  than 3600 seconds after it is inserted or accessed.

cache = VolatileHash.new(:strategy => 'lru', :max => 10)
#  LRU-based, default max is 10. That's the maximum keys to remember.

cache[:key] = "some expensive-to-calculate value, like a database query result"
cache["any key"] = "or a remote api call"

#  memo-ization:
def get_value_for(key)
    @cache ||= VolatileHash.new(:strategy => 'ttl', :ttl => 3600)
    @cache[key] ||= get_from_api(key)
end

= Test/Development

gem install bundler
bundle install
rake

= Credits

Based on a gist by github.com user joshaven at https://gist.github.com/184837

Some input from github user supertaz, considerable help on the TTL-based version.
Idea for the LRU cache developed at TrueCar Inc.