Module: Bugsage::CodeContext
- Defined in:
- lib/bugsage/code_context.rb
Class Method Summary collapse
- .escape_html(value) ⇒ Object
- .extract_location(location) ⇒ Object
- .numbered_source(file_path, line_number, context_range: 20) ⇒ Object
- .read_file_lines(file_path) ⇒ Object
- .render_code_context(file_path, line_number) ⇒ Object
Class Method Details
.escape_html(value) ⇒ Object
77 78 79 |
# File 'lib/bugsage/code_context.rb', line 77 def escape_html(value) CGI.escapeHTML(value.to_s) end |
.extract_location(location) ⇒ Object
9 10 11 12 13 14 15 16 |
# File 'lib/bugsage/code_context.rb', line 9 def extract_location(location) return [nil, nil] unless location match = location.match(/^(.+):(\d+)/) return [match[1], match[2].to_i] if match [location, nil] end |
.numbered_source(file_path, line_number, context_range: 20) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/bugsage/code_context.rb', line 50 def numbered_source(file_path, line_number, context_range: 20) lines = read_file_lines(file_path) return nil unless lines start_line = [line_number - context_range, 1].max end_line = [line_number + context_range, lines.length].min source = (start_line..end_line).map do |num| marker = num == line_number ? ">>" : " " "#{marker} #{num.to_s.rjust(4)} | #{lines[num - 1]}" end.join("\n") { start_line: start_line, end_line: end_line, error_line: line_number, source: source } end |
.read_file_lines(file_path) ⇒ Object
69 70 71 72 73 74 75 |
# File 'lib/bugsage/code_context.rb', line 69 def read_file_lines(file_path) return nil unless file_path && File.exist?(file_path) File.readlines(file_path, chomp: true) rescue StandardError nil end |
.render_code_context(file_path, line_number) ⇒ Object
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 |
# File 'lib/bugsage/code_context.rb', line 18 def render_code_context(file_path, line_number) return "" unless file_path && line_number lines = read_file_lines(file_path) return "" unless lines context_range = 5 start_line = [line_number - context_range, 1].max end_line = [line_number + context_range, lines.length].min code_html = "" (start_line..end_line).each do |num| is_error_line = num == line_number line_content = lines[num - 1] || "" error_class = is_error_line ? " error" : "" code_html += "<div class=\"code-line#{error_class}\">" code_html += "<div class=\"code-line-number\">#{num}</div>" code_html += "<div class=\"code-line-content\">#{escape_html(line_content)}</div>" code_html += "</div>" end <<~HTML <div class="code-section"> <div class="code-header">#{escape_html(file_path)}</div> <div class="code-block"> #{code_html} </div> </div> HTML end |