Sha256: 76c326a37c938a4c117e78b9c2ba8bd3b2b68283c60d6708829c1767939b5aa6

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

require "erb"
require "json"
require "securerandom"
require "stringio"

module StackTrace
  module Viz
    class HTML
      LAYOUT_FILE = "../../public/main.html.erb"
      MAX_WRITE_BYTES = 64
      MAX_JSON_NESTING = 1_000

      def initialize
        @traces = []
      end

      def save(file_path)
        file_path ||= default_file_path

        File.open(file_path, "w") do |f|
          content_io.each_line(MAX_WRITE_BYTES) { |chunk| f.write(chunk) }
        end

        file_path
      end

      def add(trace, **extra)
        traces << {
          description: "Generated by StackTrace::Viz",
          **extra,
          trace: trace
        }
      end

      private

      attr_reader :traces

      def content_io
        StringIO.new(content)
      end

      def content
        erb.result_with_hash({ trace_data: trace_data })
      end

      def trace_data
        JSON.generate(traces, max_nesting: MAX_JSON_NESTING)
      end

      def erb
        ERB.new(layout)
      end

      def layout
        File.read(layout_path)
      end

      def layout_path
        File.expand_path(LAYOUT_FILE, root_path)
      end

      def root_path
        File.dirname(__dir__)
      end

      def default_file_path
        File.expand_path(random_file_name, Dir.pwd)
      end

      def random_file_name
        "#{SecureRandom.uuid}.html"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
stack_trace-viz-0.8.0 lib/stack_trace/viz/html.rb
stack_trace-viz-0.7.0 lib/stack_trace/viz/html.rb
stack_trace-viz-0.6.0 lib/stack_trace/viz/html.rb