class ActionCounter

Constants

VERSION

Public Class Methods

new(list) click to toggle source
# File lib/action_counter.rb, line 8
def initialize(list)
  @list   = list
  @enable = true
end

Public Instance Methods

audit(action_name) { || ... } click to toggle source
# 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!() click to toggle source
# File lib/action_counter.rb, line 13
def disabled!
  @enable = false
end
enable!() click to toggle source
# File lib/action_counter.rb, line 17
def enable!
  @enable = true
end
reset() click to toggle source
# File lib/action_counter.rb, line 58
def reset
  @list.clear
end
results(sort_key: :sum) click to toggle source
# 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

Private Instance Methods

build_audit(action_name) click to toggle source
# File lib/action_counter.rb, line 69
def build_audit(action_name)
  if @enable
    ActionCounter::Audit.new(action_name: action_name, list: @list)
  else
    ActionCounter::AuditNullObject.new
  end
end
rows() click to toggle source

ex) [{action_name: 'hoge', time_sec: 1.1}]

# File lib/action_counter.rb, line 65
def rows
  @list.map { |json| JSON.parse(json) }
end