Class: SpeedGun::Source

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

Defined Under Namespace

Classes: Line

Constant Summary collapse

KEEP_RANGE =
3

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, linesamples) ⇒ Source

Returns a new instance of Source.



55
56
57
58
59
60
# File 'lib/speed_gun/source.rb', line 55

def initialize(file, linesamples)
  @id = SecureRandom.uuid
  @file = file
  @lines = []
  analyze(file, linesamples) if linesamples
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



40
41
42
# File 'lib/speed_gun/source.rb', line 40

def file
  @file
end

#idObject (readonly)

Returns the value of attribute id.



40
41
42
# File 'lib/speed_gun/source.rb', line 40

def id
  @id
end

#linesObject (readonly)

Returns the value of attribute lines.



40
41
42
# File 'lib/speed_gun/source.rb', line 40

def lines
  @lines
end

Class Method Details

.from_hash(hash, id = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/speed_gun/source.rb', line 42

def self.from_hash(hash, id = nil)
  source = new(hash['file'], nil)

  lines = (hash['lines'] || []).map do |line_id, hash|
    Line.from_hash(hash, line_id)
  end

  source.instance_variable_set(:@lines, lines)
  source.instance_variable_set(:@id, id) if id

  source
end

Instance Method Details

#analyze(file, linesamples) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/speed_gun/source.rb', line 62

def analyze(file, linesamples)
  code_lines = File.exist?(file) ? File.readlines(file) : []

  keep_lines = []
  code_lines.each_with_index do |line, idx|
    sample = linesamples[idx + 1] || [0, 0, 0, 0]
    wall, cpu, calls, allocations = *sample

    keep_lines.push(idx) if calls > 0
    @lines.push(Line.new(idx + 1, line, wall, cpu, calls, allocations))
  end

  @lines.select! do |line|
    idx = line.line - 1
    ((KEEP_RANGE * -1)..KEEP_RANGE).any? { |n| keep_lines.include?(idx + n) }
  end
end

#to_hashObject



84
85
86
87
88
89
# File 'lib/speed_gun/source.rb', line 84

def to_hash
  {
    file: file,
    lines: lines.map { |line| [ line.id, line.to_hash ] }
  }
end

#to_sObject



80
81
82
# File 'lib/speed_gun/source.rb', line 80

def to_s
  "#{file}====\n#{lines.map(&:to_s).join('')}"
end