Class: ActionCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/action_counter.rb,
lib/action_counter/version.rb

Defined Under Namespace

Classes: Audit, AuditNullObject

Constant Summary collapse

VERSION =
'0.1.1'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(list) ⇒ ActionCounter

Returns a new instance of ActionCounter.



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

def initialize(list)
  @list   = list
  @enable = true
end

Instance Method Details

#audit(action_name) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/action_counter.rb', line 21

def audit(action_name)
  audit = build_audit(action_name)

  if block_given?
    begin
      audit.start
      return yield
    ensure
      audit.stop
    end
  end
  audit
end

#disabled!Object



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

def disabled!
  @enable = false
end

#enable!Object



17
18
19
# File 'lib/action_counter.rb', line 17

def enable!
  @enable = true
end

#resetObject



58
59
60
# File 'lib/action_counter.rb', line 58

def reset
  @list.clear
end

#results(sort_key: :sum) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/action_counter.rb', line 35

def results(sort_key: :sum)
  groups = rows.group_by { |v| v['action_name'] }

  stats = groups.each.with_object([]) do |(action_name, array), results|
    stat = { action_name: action_name, count: array.size, sum: 0, min: 0, max: 0, avg: 0 }

    array.each do |hash|
      time = hash['time_sec']

      stat[:sum] += time
      stat[:min] = time if stat[:min].zero? || stat[:min] > time

      stat[:max] = time if time > stat[:max]
    end

    stat[:avg] = stat[:sum] / stat[:count]
    results << stat
  end

  sort_key = sort_key.to_sym
  stats.sort { |a, b| b[sort_key] - a[sort_key] }
end