模組 ErrorHighlight

常數

VERSION

公開類別方法

formatter() 按一下以切換來源
# File lib/error_highlight/formatter.rb, line 16
def self.formatter
  Ractor.current[:__error_highlight_formatter__] || DefaultFormatter
end
formatter=(formatter) 按一下以切換來源
# File lib/error_highlight/formatter.rb, line 20
def self.formatter=(formatter)
  Ractor.current[:__error_highlight_formatter__] = formatter
end
spot(obj, **opts) 按一下以切換來源

識別給定例外狀況發生的程式碼片段。

選項

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

限制

目前,ErrorHighlight.spot 僅支援單行程式碼片段。因此,如果傳回值不是 nil,first_lineno 和 last_lineno 會有相同的值。如果相關程式碼片段跨越多行(例如,Array#[] 的 +ary+),方法會傳回 nil。此限制可能會在未來移除。

# File lib/error_highlight/base.rb, line 33
def self.spot(obj, **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
      end

      locs = exc.backtrace_locations
      return nil unless locs

      loc = locs.first
      return nil unless loc

      opts[:name] = exc.name if NameError === obj
    end

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

    node = RubyVM::AbstractSyntaxTree.of(loc, keep_script_lines: true)

    Spotter.new(node, **opts).spot

  when RubyVM::AbstractSyntaxTree::Node
    Spotter.new(obj, **opts).spot

  else
    raise TypeError, "Exception is expected"
  end

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

  return nil
end