Created
December 29, 2011 13:32
-
-
Save ohadlevy/1534121 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Virt | |
| class Cache | |
| attr_accessor :ttl | |
| def initialize args | |
| # default TTL is one hour | |
| @ttl = args[:ttl] || 3600 | |
| reset | |
| end | |
| def store key, value | |
| @data[key] = [current_time, value] | |
| true | |
| end | |
| def read key | |
| find(key)[1] unless expired?(key) | |
| end | |
| def clear key | |
| @data[key] = nil if key | |
| end | |
| def expired? key | |
| if value = find(key) | |
| current_time - value[0] <= ttl | |
| else | |
| clear(key) | |
| end | |
| end | |
| def size | |
| @data.keys.size | |
| end | |
| def reset | |
| @data = {} | |
| end | |
| def [] key | |
| read(key) | |
| end | |
| def []= key,value | |
| store(key, value) | |
| end | |
| private # ------------------------------- | |
| def current_time | |
| Time.now | |
| end | |
| def find key | |
| return unless value = @data[key] | |
| return clear(key) unless value[0].is_a?(Time) | |
| value | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment