Sha256: 580d1f21921b2493f4ab7300b632b0374c027eb2b30e082e6d3469260c4de091

Contents?: true

Size: 1.32 KB

Versions: 4

Compression:

Stored size: 1.32 KB

Contents

module Tabs
  module Metrics
    class Counter
      include Tabs::Storage
      include Tabs::Helpers

      attr_reader :key

      def initialize(key)
        @key = key
      end

      def increment
        timestamp = Time.now.utc
        Tabs::RESOLUTIONS.each do |resolution|
          increment_resolution(resolution, timestamp)
        end
        increment_total
        true
      end

      def stats(period, resolution)
        period = normalize_period(period, resolution)
        keys = smembers("stat:keys:#{key}:#{resolution}")
        dates = keys.map { |k| extract_date_from_key(k, resolution) }
        values = mget(*keys).map(&:to_i)
        pairs = dates.zip(values)
        filtered_pairs = pairs.find_all { |p| period.cover?(p[0]) }
        filtered_pairs = fill_missing_dates(period, filtered_pairs, resolution)
        filtered_pairs.map { |p| Hash[[p]] }
      end

      def total
        get("stat:#{key}:total").to_i
      end

      private

      def increment_resolution(resolution, timestamp)
        formatted_time = Tabs::Resolution.serialize(resolution, timestamp)
        stat_key = "stat:value:#{key}:count:#{formatted_time}"
        sadd("stat:keys:#{key}:#{resolution}", stat_key)
        incr(stat_key)
      end

      def increment_total
        incr("stat:#{key}:total")
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tabs-0.5.6 lib/tabs/metrics/counter.rb
tabs-0.5.5 lib/tabs/metrics/counter.rb
tabs-0.5.4 lib/tabs/metrics/counter.rb
tabs-0.5.3 lib/tabs/metrics/counter.rb