Cache Frame#context results

This commit is contained in:
Sijawusz Pur Rahnama 2021-01-03 17:04:59 +01:00
parent 0300476813
commit d88a17f3e6

View file

@ -1,6 +1,8 @@
module Backtracer module Backtracer
# An object representation of a stack frame. # An object representation of a stack frame.
struct Backtrace::Frame struct Backtrace::Frame
@context_cache = {} of Int32 => Context
# The method of this frame (such as `User.find`). # The method of this frame (such as `User.find`).
getter method : String getter method : String
@ -109,8 +111,11 @@ module Backtracer
# See `Configuration#context_lines` # See `Configuration#context_lines`
def context(context_lines : Int32? = nil) : Context? def context(context_lines : Int32? = nil) : Context?
context_lines ||= configuration.context_lines context_lines ||= configuration.context_lines
return unless context_lines && (context_lines > 0) return unless context_lines && (context_lines > 0)
cached = @context_cache[context_lines]?
return cached if cached
return unless (lineno = @lineno) && (lineno > 0) return unless (lineno = @lineno) && (lineno > 0)
return unless (path = @path) && File.readable?(path) return unless (path = @path) && File.readable?(path)
@ -121,12 +126,13 @@ module Backtracer
pre_context = lines[Math.max(0, lineidx - context_lines), context_lines] pre_context = lines[Math.max(0, lineidx - context_lines), context_lines]
post_context = lines[Math.min(lines.size, lineidx + 1), context_lines] post_context = lines[Math.min(lines.size, lineidx + 1), context_lines]
Context.new( @context_cache[context_lines] =
lineno: lineno, Context.new(
pre: pre_context, lineno: lineno,
line: context_line, pre: pre_context,
post: post_context, line: context_line,
) post: post_context,
)
end end
end end
end end