class OwlTracer

Public Class Methods

new(timeout = 30) click to toggle source
# File lib/owl_tracer.rb, line 2
def initialize(timeout = 30)
  @stop_at = Time.now.to_f + timeout if timeout

  start
end

Public Instance Methods

dump_results(min_ms = 0) click to toggle source
# File lib/owl_tracer.rb, line 8
def dump_results(min_ms = 0)
  @trace.disable if @trace.enabled?

  result = []

  @spent.each do |call|
    if call[:time_ms] && call[:time_ms] >= min_ms
      src = call[:defined_class].name || call[:defined_class].inspect
      method_id = call[:method_id]
      if method_id.to_s.include?("_slim__") || method_id.to_s.include?("_erb__")
        method_id = "rendering"
        src = call[:path].split("/").last
      end

      src = ('  ' * call[:level]) + src

      result << "#{src}::#{method_id} (#{call[:time_ms]} ms)"
    end
  end

  result
end

Private Instance Methods

get_most_recent_unfinished_call(trace_point) click to toggle source
# File lib/owl_tracer.rb, line 59
def get_most_recent_unfinished_call(trace_point)
  @spent.reverse_each do |old|
    next unless old[:path] == trace_point.path
    next unless old[:method_id] == trace_point.method_id
    next if old[:end]

    return old
  end

  nil
end
start() click to toggle source
# File lib/owl_tracer.rb, line 33
def start
  @spent = []
  @level = 0
  @trace = TracePoint.new(:call, :return, :b_return) do |tp|
    calls_to_ignore = ["/lib/ruby/", "/gems/", "(eval)"]
    if calls_to_ignore.none? { |substr| tp.path.include?(substr) } # app's method calls only
      if tp.event == :call
        @spent << { path: tp.path, method_id: tp.method_id, defined_class: tp.defined_class,
                    start: Time.now.to_f, level: @level}
        @level += 1
      else
        last_call = get_most_recent_unfinished_call(tp)
        if last_call
          @level -= 1
          last_call[:end] = Time.now.to_f
          last_call[:time_ms] = ((last_call[:end] - last_call[:start]) * 1000).round
        end
      end
    end
    if @stop_at && Time.now.to_f > @stop_at
      @trace.disable
    end
  end
  @trace.enable
end