Sha256: 9ce4ca393fa2d3875b33b2d0182ba00bd4a0e45bd13cacf9c7c86d23796e53ca

Contents?: true

Size: 1.74 KB

Versions: 2

Compression:

Stored size: 1.74 KB

Contents

# frozen_string_literal: true

require 'binding_of_caller'

module TraceLocation
  module Collector # :nodoc:
    require_relative 'event'
    Result = Struct.new(:events, :return_value)

    def self.collect(match:, ignore:, &block)
      events = []
      hierarchy = 0
      id = 0
      cache = {}

      tracer = TracePoint.new(:call, :return) do |trace_point|
        next if match && !trace_point.path.to_s.match?(/#{match}/)
        next if ignore && trace_point.path.to_s.match?(/#{ignore}/)

        id += 1
        caller_path, caller_lineno = trace_point.binding.of_caller(2).source_location
        location_cache_key = "#{caller_path}:#{caller_lineno}"

        case trace_point.event
        when :call
          cache[location_cache_key] = hierarchy

          events << Event.new(
            id: id,
            event: trace_point.event,
            path: trace_point.path,
            lineno: trace_point.lineno,
            caller_path: caller_path,
            caller_lineno: caller_lineno,
            method_id: trace_point.method_id,
            defined_class: trace_point.defined_class,
            hierarchy: hierarchy
          )

          hierarchy += 1
        when :return
          hierarchy = cache[location_cache_key] || hierarchy

          events << Event.new(
            id: id,
            event: trace_point.event,
            path: trace_point.path,
            lineno: trace_point.lineno,
            caller_path: caller_path,
            caller_lineno: caller_lineno,
            method_id: trace_point.method_id,
            defined_class: trace_point.defined_class,
            hierarchy: hierarchy
          )
        end
      end
      return_value = tracer.enable { block.call }
      Result.new(events, return_value)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
trace_location-0.9.1 lib/trace_location/collector.rb
trace_location-0.9.0 lib/trace_location/collector.rb