Class: MemoryCache
- Inherits:
-
Object
- Object
- MemoryCache
- Defined in:
- lib/memory_cache.rb
Instance Attribute Summary collapse
-
#cache ⇒ Object
Returns the value of attribute cache.
Instance Method Summary collapse
- #fetch(key, hash = { expires_in: 1.hour }, &block) ⇒ Object
-
#initialize ⇒ MemoryCache
constructor
A new instance of MemoryCache.
- #read(key) ⇒ Object
- #validate?(key) ⇒ Boolean
- #write(key, value, hash = { expires_in: 1.hour }) ⇒ Object
Constructor Details
#initialize ⇒ MemoryCache
Returns a new instance of MemoryCache.
4 5 6 |
# File 'lib/memory_cache.rb', line 4 def initialize self.cache = {} end |
Instance Attribute Details
#cache ⇒ Object
Returns the value of attribute cache.
2 3 4 |
# File 'lib/memory_cache.rb', line 2 def cache @cache end |
Instance Method Details
#fetch(key, hash = { expires_in: 1.hour }, &block) ⇒ Object
8 9 10 |
# File 'lib/memory_cache.rb', line 8 def fetch(key, hash={ expires_in: 1.hour }, &block) validate?(key) ? read(key) : write(key, block.call, hash)['entry'] end |
#read(key) ⇒ Object
12 13 14 |
# File 'lib/memory_cache.rb', line 12 def read(key) cache[key]['entry'] end |
#validate?(key) ⇒ Boolean
20 21 22 |
# File 'lib/memory_cache.rb', line 20 def validate?(key) cache[key] && Time.now < cache[key]['valid_until'] end |
#write(key, value, hash = { expires_in: 1.hour }) ⇒ Object
16 17 18 |
# File 'lib/memory_cache.rb', line 16 def write(key, value, hash={ expires_in: 1.hour }) self.cache[key] = { 'valid_until' => (Time.now + hash[:expires_in]), 'entry' => value } unless value == '' || value == nil end |