Module: FBomb::Flowdock::Cache

Extended by:
Cache
Included in:
Cache
Defined in:
lib/fbomb/flowdock.rb

Constant Summary collapse

TTL =
3600

Instance Method Summary collapse

Instance Method Details

#_cacheObject



276
277
278
# File 'lib/fbomb/flowdock.rb', line 276

def _cache
  @_cache ||= Map.new
end

#fetch(key, &block) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/fbomb/flowdock.rb', line 280

def fetch(key, &block)
  entry = _cache[key]

  if entry
    value, cached_at = entry
    expired = (Time.now - cached_at) > TTL

    if expired
      begin
        write(key, block.call)
      rescue Object => e
        warn "#{ e.message }(#{ e.class })"
        value
      end
    else
      value
    end
  else
    write(key, block.call)
  end
end

#read(key) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/fbomb/flowdock.rb', line 253

def read(key)
  entry = _cache[key]

  return nil unless entry

  value, cached_at = entry
  expired = (Time.now - cached_at) > TTL

  if expired
    _cache.delete(key)
    nil
  else
    value
  end
end

#write(key, value) ⇒ Object



269
270
271
272
273
274
# File 'lib/fbomb/flowdock.rb', line 269

def write(key, value)
  cached_at = Time.now
  entry = [value, cached_at]
  _cache[key] = entry
  value
end