Class: Rack::Lineprof::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/lineprof/source.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name, raw_samples, options = {}) ⇒ Source

Returns a new instance of Source.



6
7
8
# File 'lib/rack/lineprof/source.rb', line 6

def initialize(file_name, raw_samples, options = {})
  @file_name, @raw_samples, @options = file_name, raw_samples, options
end

Instance Attribute Details

#file_nameObject (readonly)

Returns the value of attribute file_name.



4
5
6
# File 'lib/rack/lineprof/source.rb', line 4

def file_name
  @file_name
end

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/rack/lineprof/source.rb', line 4

def options
  @options
end

#raw_samplesObject (readonly)

Returns the value of attribute raw_samples.



4
5
6
# File 'lib/rack/lineprof/source.rb', line 4

def raw_samples
  @raw_samples
end

Instance Method Details

#formatObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/lineprof/source.rb', line 10

def format
  return nil if samples.empty?

  formatted = file_name.sub(Dir.pwd + '/', '') + "\n"

  prev_line = samples.first.line - 1
  samples.each do |sample|
    if sample.line != prev_line + 1
      formatted << color.intense_black(' ' * 14 + '.' * 7) + "\n"
    end
    prev_line = sample.line

    formatted << sample.format
  end

  formatted
end

#samplesObject



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
# File 'lib/rack/lineprof/source.rb', line 28

def samples
  @samples ||= begin
    parsed = []

    raw_samples.each_with_index do |sample, line|
      next if line == 0 # drop file info

      ms = sample[0] / 1000.0
      calls = sample[2]

      abnormal = ms >= thresholds[NOMINAL]
      near_abnormal = (line-context..line+context).any? do |near|
        near = [1, near].max
        next unless raw_samples[near]
        (raw_samples[near][0] / 1000.0) >= thresholds[NOMINAL]
      end

      next unless abnormal or near_abnormal

      threshold = thresholds.invert.detect { |th, _| ms > th }
      level = threshold ? threshold.last : CONTEXT

      next unless code = source_lines[line - 1]
      parsed << Sample.new(ms, calls, line, code, level)
    end

    parsed
  end
end

#source_linesObject



58
59
60
# File 'lib/rack/lineprof/source.rb', line 58

def source_lines
  @source_lines ||= ::File.open(file_name, 'r').to_a
end