TimeoutCache is a simple cache where objects are stored with a fixed expiration time. It is useful when you want to keep an object around for a sufficiently long period of time, but want them to disappear after, say, 5 seconds, or on the first day of next month.
gem install timeout_cache
How do I use this thing?
TimeoutCache is easy to use.
cache = . cache[:foo] = :bar cache[:foo] #=> bar # wait some time (by default, 60 seconds) cache[:foo] #=> nil
By default, retrievals return
nil 60 seconds after they're put into the cache. You can control the length of time by using
#set with the
cache.set(:a, :b, :time => 5) cache[:a] #=> :b sleep 5 cache[:a] #=> nil
You can also use an instance of
cache.set(:x, :y, :time => Time.now + 50)
You can use any object as the value for
:time provided it is an
Time, has a
to_int method, or has a
If you want to change the default expiration time, do so when you make a new instance of
TimeoutCache by passing the length of time in seconds.
cache = .(10 * 60 * 60) # 10 hours
Unless an object is added to the cache using the
:time option, the default is used. This default length of time is 60 seconds.
Entry deletion and pruning
Expired entries are deleted lazily to try and avoid to cost of excessively pruning. If an entry is added with an expire time of 15 seconds and nothing touches the cache, the entry will still be in the cache after 20 seconds. Expired entries are deleted when certain methods are called:
#get) provided that the entry being retrieved has expired
If you want to manually prune the cache, you may do so by calling
There's not much to the code, but it's all commented and you can generate documentation with
You can run the tests with
License / Copyright
Copyright (c) 2012 Adam Prescott, released under the MIT license. See the LICENSE file for details.
The official repository is on GitHub at aprescott/timeout_cache. Issues should be opened there, as well as pull requests. Submissions should be on a separate feature branch:
- Fork and clone
- Create a feature branch
- Add code and tests
- Run all the tests
- Push you branch to your GitHub repository
- Send a pull request
Your contribution will be assumed to also be licensed under the MIT license.