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



267
268
269
# File 'lib/fbomb/flowdock.rb', line 267

def _cache
  @_cache ||= Map.new
end

#fetch(key, &block) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/fbomb/flowdock.rb', line 271

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



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/fbomb/flowdock.rb', line 244

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



260
261
262
263
264
265
# File 'lib/fbomb/flowdock.rb', line 260

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