From 7b1feda061b3260348c35479fe4426d261239ac7 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Fri, 4 Mar 2011 12:54:50 +0000 Subject: [PATCH] added key grouping for statistics Hash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Example: store(“message”, {“count/private” => 1}) store(“message”, {“count/public” => 1}) fetch("message", 2.minutes.ago, Time.now) #=> { "count" => 2, "count/private" => 1, "count/public" => 1 } --- lib/redistat.rb | 1 + lib/redistat/summary.rb | 21 +++++++++++++++++++++ spec/summary_spec.rb | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/lib/redistat.rb b/lib/redistat.rb index f95cefc..6a230b5 100644 --- a/lib/redistat.rb +++ b/lib/redistat.rb @@ -36,6 +36,7 @@ module Redistat KEY_EVENT = ".event:" KEY_LEBELS = "Redistat.lables:" KEY_EVENT_IDS = ".event_ids" + GROUP_SEPARATOR = "/" class InvalidOptions < ArgumentError; end class RedisServerIsTooOld < Exception; end diff --git a/lib/redistat/summary.rb b/lib/redistat/summary.rb index 5dbcab1..e955812 100644 --- a/lib/redistat/summary.rb +++ b/lib/redistat/summary.rb @@ -4,6 +4,7 @@ module Redistat def self.update_all(key, stats = {}, depth_limit = nil, connection_ref = nil) stats ||= {} + stats = inject_group_summaries(stats) depth_limit ||= key.depth return nil if stats.size == 0 Date::DEPTHS.each do |depth| @@ -20,5 +21,25 @@ module Redistat end end + def self.inject_group_summaries!(stats) + stats.each do |key, value| + parts = key.to_s.split(GROUP_SEPARATOR) + parts.pop + if parts.size > 0 + sum_parts = [] + parts.each do |part| + sum_parts << part + sum_key = sum_parts.join(GROUP_SEPARATOR) + (stats.has_key?(sum_key)) ? stats[sum_key] += value : stats[sum_key] = value + end + end + end + stats + end + + def self.inject_group_summaries(stats) + inject_group_summaries!(stats.clone) + end + end end \ No newline at end of file diff --git a/spec/summary_spec.rb b/spec/summary_spec.rb index eadcdbb..3c05635 100644 --- a/spec/summary_spec.rb +++ b/spec/summary_spec.rb @@ -46,4 +46,25 @@ describe Redistat::Summary do end end + it "should inject stats key grouping summaries" do + hash = { "count/hello" => 3, "count/world" => 7, + "death/bomb" => 4, "death/unicorn" => 3, + :"od/sugar" => 7, :"od/meth" => 8 } + res = Redistat::Summary.send(:inject_group_summaries, hash) + res.should == { "count" => 10, "count/hello" => 3, "count/world" => 7, + "death" => 7, "death/bomb" => 4, "death/unicorn" => 3, + "od" => 15, :"od/sugar" => 7, :"od/meth" => 8 } + end + + it "should properly store key group summaries" do + stats = {"views" => 3, "visitors/eu" => 2, "visitors/us" => 4} + Redistat::Summary.update_all(@key, stats, :hour) + summary = db.hgetall(@key.to_s(:hour)) + summary.should have(4).items + summary["views"].should == "3" + summary["visitors"].should == "6" + summary["visitors/eu"].should == "2" + summary["visitors/us"].should == "4" + end + end