Class: Von::Counters::Period

Inherits:
Object
  • Object
show all
Includes:
Commands
Defined in:
lib/von/counters/period.rb

Instance Method Summary collapse

Methods included from Commands

#hdel, #hget, #hgetall, #hincrby, #hset, #llen, #lpop, #lrange, #rpush

Constructor Details

#initialize(field, periods = nil) ⇒ Period

Returns a new instance of Period.



6
7
8
9
# File 'lib/von/counters/period.rb', line 6

def initialize(field, periods = nil)
  @field   = field.to_sym
  @periods = periods || []
end

Instance Method Details

#count(time_unit) ⇒ Object

Count the fields for the given time period for this Counter.

Returns an Array of Hashes representing the count



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/von/counters/period.rb', line 44

def count(time_unit)
  return if @periods.empty?

  counts     = []
  this_period = nil
  _period     = @periods.select { |p| p.time_unit == time_unit }.first

  _period.length.times do |i|
    this_period = _period.prev(i)
    counts.unshift(this_period)
  end

  keys = hgetall(hash_key(time_unit))
  counts.map { |date| { :timestamp => date, :count => keys.fetch(date, 0).to_i }}
end

#hash_key(time_unit) ⇒ Object

Returns the Redis hash key used for storing counts for this Period



12
13
14
# File 'lib/von/counters/period.rb', line 12

def hash_key(time_unit)
  "#{Von.config.namespace}:counters:#{@field}:#{time_unit}"
end

#incrementObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/von/counters/period.rb', line 21

def increment
  return if @periods.empty?

  @periods.each do |period|
    _hash_key = hash_key(period.time_unit)
    _list_key = list_key(period.time_unit)

    hincrby(_hash_key, period.timestamp, 1)

    unless lrange(_list_key, 0, -1).include?(period.timestamp)
      rpush(_list_key, period.timestamp)
    end

    if llen(_list_key) > period.length
      expired_counter = lpop(_list_key)
      hdel(_hash_key, expired_counter)
    end
  end
end

#list_key(time_unit) ⇒ Object

Returns the Redis list key used for storing current “active” counters



17
18
19
# File 'lib/von/counters/period.rb', line 17

def list_key(time_unit)
  "#{Von.config.namespace}:lists:#{@field}:#{time_unit}"
end