class RefreshingCache

Constants

VERSION

Attributes

check_proc[R]
refresh_proc[R]
timeout[R]
timeouts[R]

Public Class Methods

new(timeout: timeout, check_proc: check_proc, value_proc: value_proc) click to toggle source
Calls superclass method
# File lib/refreshing_cache.rb, line 6
def initialize(timeout: timeout, check_proc: check_proc, value_proc: value_proc)
  @timeout = timeout

  @check_proc = check_proc
  @refresh_proc = value_proc

  # Stores key => timeout info
  @timeouts = {}

  # Actual underlying data we're caching
  @hash = {}
  super(@hash)
end

Public Instance Methods

[](key) click to toggle source
Calls superclass method
# File lib/refreshing_cache.rb, line 20
def [](key)
  self[key] = refresh!(key) if regenerate_value?(key)
  super
end
refresh!(key) click to toggle source
# File lib/refreshing_cache.rb, line 25
def refresh!(key)
  val = refresh_proc.call(key, timeouts[key])
  timeouts[key] = Time.now
  val
end

Protected Instance Methods

regenerate_value?(key) click to toggle source
# File lib/refreshing_cache.rb, line 34
def regenerate_value?(key)
  # No timeout info? We need to generate values.
  return true unless timeouts.has_key?(key)

  # If we've timed out, force a check
  return false if timeouts[key] + timeout > Time.now

  check_proc.call(key, timeouts[key])
end