Class: MotionProfiler::Report

Inherits:
Object
  • Object
show all
Defined in:
lib/motion-profiler/report.rb

Overview

Sorts and displays data collected by a Profiler.

Constant Summary collapse

FIELDS =

Fields that can be passed to #sort_by.

[:method, :min, :max, :average, :total_time, :total_calls]
DIRECTIONS =

Directions that can be passed to #order.

[:asc, :desc,]

Instance Method Summary collapse

Constructor Details

#initialize(data, name) ⇒ Report

Initializes a new Report.



21
22
23
24
25
26
# File 'lib/motion-profiler/report.rb', line 21

def initialize(data, name)
  @data = data
  @name = name
  @sort_by = :average
  @order = :descending
end

Instance Method Details

#order(direction) ⇒ Object

Changes the direction of the sort. Defaults to ‘:desc`. Chainable with #sort_by.



39
40
41
42
43
44
# File 'lib/motion-profiler/report.rb', line 39

def order(direction)
  direction = direction.to_sym
  direction = :desc unless DIRECTIONS.include?(direction)
  @order = direction
  self
end

#sort_by(field) ⇒ Object

Sorts the report by the given field. Defaults to ‘:average`. Chainable with #order.



30
31
32
33
34
35
# File 'lib/motion-profiler/report.rb', line 30

def sort_by(field)
  field = field.to_sym
  field = :average unless FIELDS.include?(field)
  @sort_by = field
  self
end

#to_aObject

Sorts the data by order and sort_by and returns an array.



47
48
49
50
51
52
53
# File 'lib/motion-profiler/report.rb', line 47

def to_a
  if @order == :asc
    @data.sort { |a, b| a[@sort_by] <=> b[@sort_by] }
  else
    @data.sort { |a, b| b[@sort_by] <=> a[@sort_by] }
  end
end

#to_sObject

Returns a printable string of the sorted data.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/motion-profiler/report.rb', line 56

def to_s
  string = "\nVelocity results for: #{@name}\n".light_blue
  self.to_a.each do |method_data|
    string += "-- #{method_data.shift[1]}\n".red
    method_data.each_pair do |metric, time|
      if time.is_a?(Float)
        time = time.to_ms
      end
      string += "  #{metric}: #{time}\n"
    end
  end
  return string
end