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.



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

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.



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

def file_name
  @file_name
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

#raw_samplesObject (readonly)

Returns the value of attribute raw_samples.



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

def raw_samples
  @raw_samples
end

Instance Method Details

#format(colorize = true) ⇒ Object



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

def format colorize = true
  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



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

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



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

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