Class: NPlusInsight::SourceLocation

Inherits:
Struct
  • Object
show all
Defined in:
lib/n_plus_insight/source_location.rb

Constant Summary collapse

FRAME_PATTERN =
/\A(.+?):(\d+)(?::in [`'](.+)[`'])?\z/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#labelObject

Returns the value of attribute label

Returns:

  • (Object)

    the current value of label



2
3
4
# File 'lib/n_plus_insight/source_location.rb', line 2

def label
  @label
end

#lineObject

Returns the value of attribute line

Returns:

  • (Object)

    the current value of line



2
3
4
# File 'lib/n_plus_insight/source_location.rb', line 2

def line
  @line
end

#pathObject

Returns the value of attribute path

Returns:

  • (Object)

    the current value of path



2
3
4
# File 'lib/n_plus_insight/source_location.rb', line 2

def path
  @path
end

#snippetObject

Returns the value of attribute snippet

Returns:

  • (Object)

    the current value of snippet



2
3
4
# File 'lib/n_plus_insight/source_location.rb', line 2

def snippet
  @snippet
end

Class Method Details

.from(caller_lines) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/n_plus_insight/source_location.rb', line 5

def self.from(caller_lines)
  root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s.tr("\\", "/") : nil
  frame = caller_lines.find do |entry|
    path = entry.to_s.tr("\\", "/")
    root ? path.start_with?("#{root}/app/", "#{root}/lib/") : !path.include?("/gems/")
  end
  return unless frame

  match = FRAME_PATTERN.match(frame.to_s)
  return unless match

  path, line, label = match.captures
  line = line.to_i
  new(path: path, line: line, label: label, snippet: read_snippet(path, line))
end

.read_snippet(path, line) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/n_plus_insight/source_location.rb', line 21

def self.read_snippet(path, line)
  lines = File.readlines(path)
  first = [line - 3, 0].max
  lines[first, 5].to_a.each_with_index.map do |text, index|
    { line: first + index + 1, text: text.chomp, active: first + index + 1 == line }
  end
rescue SystemCallError, ArgumentError
  []
end

Instance Method Details

#as_jsonObject



31
32
33
# File 'lib/n_plus_insight/source_location.rb', line 31

def as_json(*)
  { path: path, line: line, label: label, snippet: snippet }
end