Skip to content

Instantly share code, notes, and snippets.

@mdub
Created May 20, 2009 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdub/114618 to your computer and use it in GitHub Desktop.
Save mdub/114618 to your computer and use it in GitHub Desktop.
# A Hash derivative that is automatically cleared every so often
class PeriodicallyClearedHash
def initialize(period, &default_value_calculator)
@period = period.to_i
@default_value_calculator = default_value_calculator || lambda { nil }
end
attr_reader :period
private
def default_value_for(key)
@default_value_calculator.call(key)
end
def current_hash
reset_if_time_slice_changed
@current_hash ||= Hash.new do |h, key|
h[key] = default_value_for(key)
end
end
def reset_if_time_slice_changed
time_slice = Time.now.to_i / period
unless @current_time_slice == time_slice
@current_time_slice = time_slice
@current_hash = nil
end
end
def method_missing(method, *args)
current_hash.__send__(method, *args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment