Module: TraceFiles

Defined in:
lib/trace_files.rb,
lib/trace_files/version.rb

Constant Summary collapse

VERSION =
'1.0.0'
DATE =
'2015-06-18'

Class Method Summary collapse

Class Method Details

.set(spec_opts) ⇒ TracePoint

Trace file source to :io (default $stdout)

spec_opts = {}

Parameters:

  • :trace (Array<String>)

    the files to trace

  • :io (IO)

    io to print to

Returns:

  • (TracePoint)

    the trace point object



12
13
14
15
16
17
18
19
20
21
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
# File 'lib/trace_files.rb', line 12

def self.set spec_opts
  targets   = []
  files     = {}
  last_file = ''
  last_line = -1

  files_to_trace = spec_opts.fetch(:trace, []);
  io    = spec_opts.fetch(:io, $stdout)
  color = spec_opts.fetch(:color, "\e[32m") # ANSI.green default
  # target only existing readable files
  files_to_trace.each do |f|
    if File.exists?(f) && File.readable?(f)
      targets.push File.expand_path f
      targets.push File.basename f # sometimes the file is relative
    end
  end
  return if targets.empty?

  trace_point = TracePoint.new do |trace|
    file_path = trace.path
    if targets.include?(file_path)
      line_number = trace.lineno
      # never repeat a line
      unless file_path == last_file && line_number == last_line
        file_sym        = file_path.intern
        files[file_sym] = IO.readlines(file_path) if files[file_sym].nil?
        lines           = files[file_sym]

        # arrays are 0 indexed and line numbers start at one.
        io.print color if color # ANSI code
        io.puts lines[line_number - 1]
        io.print "\e[0m" if color # ANSI.clear

        last_file = file_path
        last_line = line_number
      end
    end
  end

  trace_point.enable
  trace_point
end