Class: RubySnooper::TraceWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_snooper/trace_writer.rb

Defined Under Namespace

Classes: Line, Return

Instance Method Summary collapse

Constructor Details

#initialize(method_name, caller_path) ⇒ TraceWriter

Returns a new instance of TraceWriter.



5
6
7
8
9
10
11
# File 'lib/ruby_snooper/trace_writer.rb', line 5

def initialize(method_name, caller_path)
  @method_name = method_name
  @caller_path = caller_path
  @source_cache = {}
  @lines = []
  @return = nil
end

Instance Method Details

#code_for(filename) ⇒ Object



13
14
15
# File 'lib/ruby_snooper/trace_writer.rb', line 13

def code_for(filename)
  @source_cache[filename] ||= IO.readlines(filename, chomp: true)
end


17
18
19
20
# File 'lib/ruby_snooper/trace_writer.rb', line 17

def print
  @lines.each(&:print)
  @return.print
end

#trace_pointObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby_snooper/trace_writer.rb', line 22

def trace_point
  @trace_point ||= TracePoint.new(:call, :line, :return) do |tp|
    next if @method_name != tp.method_id
    next if tp.path != @caller_path

    local_variables = tp.binding.local_variables.map do |name|
      [name, tp.binding.local_variable_get(name).inspect]
    end.to_h

    if @lines.count > 0
      new_variables = local_variables.select { |key,value| !@lines.last.local_variables.has_key?(key) }
      modified_variables = local_variables.select {|key, value| @lines.last.local_variables.has_key?(key) && value != @lines.last.local_variables[key] }
    end

    case tp.event
    when :call, :line
      @lines << Line.new(
        tp.method_id,
        tp.event,
        tp.lineno,
        Time.now,
        code_for(tp.path)[tp.lineno - 1],
        local_variables,
        new_variables,
        modified_variables,
        tp.path,
      )
    when :return
      @return = Return.new(
        tp.method_id,
        tp.event,
        tp.lineno,
        Time.now,
        code_for(tp.path)[tp.lineno - 1],
        tp.return_value,
        tp.path,
      )
    end
  end
end