Class: MockSuey::Tracer::TracePointCollector

Inherits:
Object
  • Object
show all
Defined in:
lib/mock_suey/tracer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tracer) ⇒ TracePointCollector

Returns a new instance of TracePointCollector.



56
57
58
# File 'lib/mock_suey/tracer.rb', line 56

def initialize(tracer)
  @tracer = tracer
end

Instance Attribute Details

#tracerObject (readonly)

Returns the value of attribute tracer.



54
55
56
# File 'lib/mock_suey/tracer.rb', line 54

def tracer
  @tracer
end

Instance Method Details

#setup(targets) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/mock_suey/tracer.rb', line 60

def setup(targets)
  tracer = self.tracer
  calls_stack = []

  @tp = TracePoint.trace(:call, :return) do |tp|
    methods = targets[tp.defined_class]
    next unless methods
    next unless methods.include?(tp.method_id)

    receiver_class, method_name = tp.defined_class, tp.method_id

    if tp.event == :call
      method = tp.self.method(method_name)
      arguments = []
      kwargs = {}

      method.parameters.each do |(type, name)|
        next if name == :** || name == :* || name == :&

        val = tp.binding.local_variable_get(name)

        case type
        when :req, :opt
          arguments << val
        when :keyreq, :key
          kwargs[name] = val
        when :rest
          arguments.concat(val)
        when :keyrest
          kwargs.merge!(val)
        end
      end

      arguments << kwargs unless kwargs.empty?

      call_obj = MethodCall.new(
        receiver_class:,
        method_name:,
        arguments:,
        has_kwargs: !kwargs.empty?,
        metadata: {
          location: method.source_location.first
        }
      )
      tracer << call_obj
      calls_stack << call_obj
    elsif tp.event == :return
      call_obj = calls_stack.pop
      call_obj.return_value = tp.return_value
    end
  end
end

#stopObject



113
114
115
# File 'lib/mock_suey/tracer.rb', line 113

def stop
  tp.disable
end