Class: MemoryCache

Inherits:
Object
  • Object
show all
Defined in:
lib/fragment_client/memory_cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMemoryCache

Returns a new instance of MemoryCache.



4
5
6
# File 'lib/fragment_client/memory_cache.rb', line 4

def initialize
  self.cache = {}
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



2
3
4
# File 'lib/fragment_client/memory_cache.rb', line 2

def cache
  @cache
end

Instance Method Details

#fetch(key, &block) ⇒ Object



8
9
10
# File 'lib/fragment_client/memory_cache.rb', line 8

def fetch(key, &block)
  validate?(key) ? read(key) : write(key, block.call)['entry']
end

#read(key) ⇒ Object



12
13
14
# File 'lib/fragment_client/memory_cache.rb', line 12

def read(key)
  cache[key]['entry']
end

#validate?(key) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/fragment_client/memory_cache.rb', line 20

def validate?(key)
  cache[key] && (Time.now - cache[key]['created_at']) < 1.hours
end

#write(key, value) ⇒ Object



16
17
18
# File 'lib/fragment_client/memory_cache.rb', line 16

def write(key, value)
  self.cache[key] = { 'created_at' => Time.now, 'entry' => value } unless value.blank?
end