Class: MethodProfiler::Report

Inherits:
Object
  • Object
show all
Defined in:
lib/method_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_calls]
DIRECTIONS =

Directions that can be passed to #order.

[:asc, :ascending, :desc, :descending]

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Report

Initializes a new MethodProfiler::Report. Used to sort and display data collected by a Profiler.

Parameters:

  • data (Array)

    Data collected by a Profiler.



18
19
20
21
22
# File 'lib/method_profiler/report.rb', line 18

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

Instance Method Details

#order(direction) ⇒ Report

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

Parameters:

  • direction (Symbol, String)

    Any direction from DIRECTIONS to direct the sort.

Returns:



41
42
43
44
45
46
47
48
# File 'lib/method_profiler/report.rb', line 41

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

#sort_by(field) ⇒ Report

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

Parameters:

  • field (Symbol, String)

    Any field from FIELDS to sort by.

Returns:



29
30
31
32
33
34
# File 'lib/method_profiler/report.rb', line 29

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

#to_aArray

Sorts the data by the currently set criteria and returns an array of profiling results.

Returns:

  • (Array)

    An array of profiling results.



54
55
56
57
58
59
60
# File 'lib/method_profiler/report.rb', line 54

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

#to_sString

Sorts the data by the currently set criteria and returns a pretty printed table as a string.

Returns:

  • (String)

    A table of profiling results.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/method_profiler/report.rb', line 66

def to_s
  [
    "MethodProfiler results for: #{@obj}",
    Hirb::Helpers::Table.render(
      to_a,
      :headers => {
        :method => "Method",
        :min => "Min Time",
        :max => "Max Time",
        :average => "Average Time",
        :total_calls => "Total Calls"
      },
      :fields => [:method, :min, :max, :average, :total_calls],
      :filters => {
        :min => :to_milliseconds,
        :max => :to_milliseconds,
        :average => :to_milliseconds
      },
      :description => false
    )
  ].join("\n")
end