Created
May 20, 2009 04:36
-
-
Save mdub/114618 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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