Class: Conscriptor::EventCounter

Inherits:
Object
  • Object
show all
Includes:
Histogram
Defined in:
lib/conscriptor/event_counter.rb

Instance Method Summary collapse

Methods included from Histogram

#histogram

Constructor Details

#initialize(logger = simple_logger) ⇒ EventCounter

Returns a new instance of EventCounter.



8
9
10
11
# File 'lib/conscriptor/event_counter.rb', line 8

def initialize(logger=simple_logger)
  @logger = logger
  clear
end

Instance Method Details

#[](event) ⇒ Object



28
29
30
# File 'lib/conscriptor/event_counter.rb', line 28

def [](event)
  @counts[event]
end

#clear(*keys) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/conscriptor/event_counter.rb', line 36

def clear(*keys)
  if keys.empty?
    @counts = {}
    @errors = {}
  else
    keys.each do |key|
      @counts.delete(key)
      @errors.delete(key)
    end
  end
  @key = {}
end

#dumpObject



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/conscriptor/event_counter.rb', line 61

def dump
  @logger.info("\n#{@counts.sort_by { |_k, v| -v }.map { |k, v| "#{k} = #{v}" }.join("\n")}")

  unless @errors.empty?
    require 'colorize'

    @errors.each do |event, errors|
      @logger.info "Error #{event} (#{errors.count}):\n#{histogram(errors)}".red
    end
  end

  print_key
end

#empty?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/conscriptor/event_counter.rb', line 49

def empty?
  @counts.empty?
end

#errors?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/conscriptor/event_counter.rb', line 53

def errors?
  !@errors.empty?
end


75
76
77
78
79
80
81
82
# File 'lib/conscriptor/event_counter.rb', line 75

def print_key
  return if @key.empty?

  puts "\nKey"
  @key.each do |event, symbol|
    puts "    #{symbol} = #{event} (#{@counts[event]})"
  end
end

#record(event) ⇒ Object



13
14
15
# File 'lib/conscriptor/event_counter.rb', line 13

def record(event)
  record_many(event, 1)
end

#record_and_print(symbol, event) ⇒ Object



17
18
19
20
21
# File 'lib/conscriptor/event_counter.rb', line 17

def record_and_print(symbol, event)
  record(event)
  print symbol
  @key[event] = symbol
end

#record_error(event, error) ⇒ Object



32
33
34
# File 'lib/conscriptor/event_counter.rb', line 32

def record_error(event, error)
  (@errors[event] ||= []) << error
end

#record_many(event, how_many) ⇒ Object



23
24
25
26
# File 'lib/conscriptor/event_counter.rb', line 23

def record_many(event, how_many)
  @counts[event] ||= 0
  @counts[event] += how_many
end

#to_hObject



84
85
86
# File 'lib/conscriptor/event_counter.rb', line 84

def to_h
  @counts
end

#to_sObject



57
58
59
# File 'lib/conscriptor/event_counter.rb', line 57

def to_s
  @counts.map { |k, v| "#{k} = #{v}" }.sort.join(', ')
end