Created
March 25, 2010 22:59
-
-
Save jkriss/344240 to your computer and use it in GitHub Desktop.
This file contains 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
class Statter | |
def initialize | |
@stat_calcuations = {} | |
@results = {} | |
end | |
def stat_calcuation(name, args, &block) | |
@stat_calcuations[name] = StatCalculation.new(name, args, block) | |
end | |
def update(name, args) | |
stat = @stat_calcuations[name] | |
key = stat.key_for_args(args) | |
result = stat.get_result(args) | |
@results[key] = result | |
end | |
def updated?(name, args, since) | |
result = get_result(name, args) | |
return result.last_updated > since | |
end | |
def get(name, args) | |
result = get_result(name, args) | |
result ? result.value : nil | |
end | |
def get_result(name, args) | |
@results[StatCalculation.key_for_name_and_args(name, args)] | |
end | |
class StatCalculation < Struct.new(:name, :args, :block) | |
def StatCalculation.key_for_name_and_args(name, args) | |
"#{name}_#{args.join(':')}" | |
end | |
def key_for_args(args) | |
StatCalculation.key_for_name_and_args(name, args) | |
end | |
def get_result(args) | |
Result.new(key_for_args(args), self.block.call(args), Time.now) | |
end | |
end | |
class Result < Struct.new(:key, :value, :last_updated) | |
end | |
end | |
statter = Statter.new | |
statter.stat_calcuation :multiply, [:a, :b] do |a,b| | |
a * b | |
end | |
puts "multiply 2x10? #{statter.get(:multiply, [2,10])} (not set yet)" | |
statter.update(:multiply, [2,10]) | |
puts "multiply 2x10? #{statter.get(:multiply, [2,10])}" | |
last_check = Time.now | |
puts "anything new for multiply 2x10? #{statter.updated?(:multiply, [2,10], last_check)}" | |
statter.update(:multiply, [2,10]) | |
puts "anything new for multiply 2x10? #{statter.updated?(:multiply, [2,10], last_check)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment