Sha256: 7262e45e60359018cbbf21098bc5878e2f6cdf105ebd1357f9cac917f7ba041f

Contents?: true

Size: 1.36 KB

Versions: 2

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module Orthoses
  # Trace :call event by TracePoint and capture arguments.
  #   def call
  #     scope = CallTracer.new
  #     scope.trace(ActiveRecord::Base.method(:scope)) do
  #       @loader.call
  #     end
  #     scope.result.each do |method, argument|
  #       argument[:name]
  #       argument[:body]
  #       argument[:block]
  #     end
  class CallTracer
    attr_accessor :result

    def initialize
      @result = []
    end

    def trace(target, &block)
      TracePoint.new(:call) do |tp|
        called_method = tp.self.method(tp.method_id)
        argument = tp.parameters.each_with_object({}) do |op_name, hash|
          name = op_name[1]
          case name
          when :*, :**, :&, nil
            # skip
          else
            hash[name] = tp.binding.local_variable_get(name).then do |var|
              case var
              when Module
                var # avoid missing name
              else
                var.dup
              end
            rescue => err
              case var
              when Thread::Backtrace::Location
                # known
              else
                warn("#dup fail (#{err.class}) #{err.message}")
              end
              var
            end
          end
        end
        @result << [called_method, argument]
      end.enable(target: target, &block)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
orthoses-0.2.0 lib/orthoses/call_tracer.rb
orthoses-0.1.0 lib/orthoses/call_tracer.rb