Class: Von::Counters::Current

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

Instance Method Summary collapse

Methods included from Commands

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

Constructor Details

#initialize(field, periods = nil) ⇒ Current

Initialize a new Counter

field - counter field name



9
10
11
12
# File 'lib/von/counters/current.rb', line 9

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

Instance Method Details

#count(time_unit) ⇒ Object



36
37
38
39
# File 'lib/von/counters/current.rb', line 36

def count(time_unit)
  count = hget("#{hash_key}:#{time_unit}", 'total')
  count.nil? ? 0 : count.to_i
end

#current_timestamp(time_unit) ⇒ Object



19
20
21
# File 'lib/von/counters/current.rb', line 19

def current_timestamp(time_unit)
  hget("#{hash_key}:#{time_unit}", 'timestamp')
end

#hash_keyObject

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



15
16
17
# File 'lib/von/counters/current.rb', line 15

def hash_key
  "#{Von.config.namespace}:counters:currents:#{@field}"
end

#incrementObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/von/counters/current.rb', line 23

def increment
  return if @periods.empty?

  @periods.each do |period|
    if period.timestamp != current_timestamp(period.time_unit)
      hset("#{hash_key}:#{period.time_unit}", 'total', 1)
      hset("#{hash_key}:#{period.time_unit}", 'timestamp', period.timestamp)
    else
      hincrby("#{hash_key}:#{period.time_unit}", 'total', 1)
    end
  end
end