module ErrorHighlight



Public Class Methods

formatter() click to toggle source
# File error_highlight/formatter.rb, line 16
def self.formatter
  Ractor.current[:__error_highlight_formatter__] || DefaultFormatter
formatter=(formatter) click to toggle source
# File error_highlight/formatter.rb, line 20
def self.formatter=(formatter)
  Ractor.current[:__error_highlight_formatter__] = formatter
spot(obj, **opts) click to toggle source

Identify the code fragment at that a given exception occurred.


point_type: :name | :args

:name (default) points the method/variable name that the exception occurred.
:args points the arguments of the method call that the exception occurred.

backtrace_location: Thread::Backtrace::Location

It locates the code fragment of the given backtrace_location.
By default, it uses the first frame of backtrace_locations of the given exception.


  first_lineno: Integer,
  first_column: Integer,
  last_lineno: Integer,
  last_column: Integer,
  snippet: String,
  script_lines: [String],
} | nil


Currently, only supports a single-line code fragment. Therefore, if the return value is not nil, first_lineno and last_lineno will have the same value. If the relevant code fragment spans multiple lines (e.g., Array#[] of +ary+), the method will return nil. This restriction may be removed in the future.

# File error_highlight/base.rb, line 33
def, **opts)
  case obj
  when Exception
    exc = obj
    loc = opts[:backtrace_location]
    opts = { point_type: opts.fetch(:point_type, :name) }

    unless loc
      case exc
      when TypeError, ArgumentError
        opts[:point_type] = :args

      locs = exc.backtrace_locations
      return nil unless locs

      loc = locs.first
      return nil unless loc

      opts[:name] = if NameError === obj

    return nil unless Thread::Backtrace::Location === loc

    node =
        RubyVM::AbstractSyntaxTree.of(loc, keep_script_lines: true)
      rescue RuntimeError => error
        # RubyVM::AbstractSyntaxTree.of raises an error with a message that
        # includes "prism" when the ISEQ was compiled with the prism compiler.
        # In this case, we'll set the node to `nil`. In the future, we will
        # reparse with the prism parser and pass the parsed node to Spotter.
        raise unless error.message.include?("prism")
      end, **opts).spot

  when RubyVM::AbstractSyntaxTree::Node, **opts).spot

    raise TypeError, "Exception is expected"

rescue SyntaxError,
       SystemCallError, # file not found or something
       ArgumentError # eval'ed code

  return nil