Class: Cache
- Inherits:
-
Object
- Object
- Cache
- Defined in:
- lib/libcache/cache.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#expiry_time ⇒ Object
Returns the value of attribute expiry_time.
-
#max_size ⇒ Object
Returns the value of attribute max_size.
-
#refresh ⇒ Object
Returns the value of attribute refresh.
-
#store ⇒ Object
Returns the value of attribute store.
Instance Method Summary collapse
- #check_refresh(key) ⇒ Object
- #create_store ⇒ Object
- #exists?(key) ⇒ Boolean
- #get(key) ⇒ Object
- #has_refresh? ⇒ Boolean
-
#initialize ⇒ Cache
constructor
A new instance of Cache.
- #invalidate(key) ⇒ Object
- #invalidateAll ⇒ Object
- #put(key, value) ⇒ Object
Constructor Details
#initialize ⇒ Cache
Returns a new instance of Cache.
8 9 10 11 12 |
# File 'lib/libcache/cache.rb', line 8 def initialize ENV['TZ'] = 'UTC' @scheduler = Rufus::Scheduler.new @time_tracker = Hash.new end |
Instance Attribute Details
#expiry_time ⇒ Object
Returns the value of attribute expiry_time.
6 7 8 |
# File 'lib/libcache/cache.rb', line 6 def expiry_time @expiry_time end |
#max_size ⇒ Object
Returns the value of attribute max_size.
6 7 8 |
# File 'lib/libcache/cache.rb', line 6 def max_size @max_size end |
#refresh ⇒ Object
Returns the value of attribute refresh.
6 7 8 |
# File 'lib/libcache/cache.rb', line 6 def refresh @refresh end |
#store ⇒ Object
Returns the value of attribute store.
6 7 8 |
# File 'lib/libcache/cache.rb', line 6 def store @store end |
Instance Method Details
#check_refresh(key) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/libcache/cache.rb', line 44 def check_refresh(key) if @cache[key] == nil && !has_refresh? val = refresh.call(key) put(key, val) return val end end |
#create_store ⇒ Object
14 15 16 |
# File 'lib/libcache/cache.rb', line 14 def create_store @cache = Hash.new end |
#exists?(key) ⇒ Boolean
39 40 41 |
# File 'lib/libcache/cache.rb', line 39 def exists?(key) return @cache.key?(key) end |
#get(key) ⇒ Object
34 35 36 37 |
# File 'lib/libcache/cache.rb', line 34 def get(key) check_refresh(key) return @cache[key] end |
#has_refresh? ⇒ Boolean
52 53 54 |
# File 'lib/libcache/cache.rb', line 52 def has_refresh? return refresh == nil end |
#invalidate(key) ⇒ Object
56 57 58 |
# File 'lib/libcache/cache.rb', line 56 def invalidate(key) @cache.delete key end |
#invalidateAll ⇒ Object
60 61 62 |
# File 'lib/libcache/cache.rb', line 60 def invalidateAll @cache.clear end |
#put(key, value) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/libcache/cache.rb', line 18 def put(key, value) # removed oldest entry if max_size is approached if max_size != nil if @cache.size >= max_size key, value = @time_tracker.values.sort {|v| Time.now - v }.reverse.first invalidate(key) @time_tracker.delete(key) end @time_tracker[key] = Time.now end @cache[key] = value @scheduler.in expiry_time, :blocking => true do invalidate key end end |