Sha256: fc29c1c402d95fc7ec18fe02f0e3a08b77235230f2b235adcf3baa0a841e8127

Contents?: true

Size: 1.61 KB

Versions: 5

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

require "refinements/array"
require "refinements/pathname"

module Tocer
  # Writes table of contents to a Markdown document.
  # :reek:DataClump
  class Writer
    using Refinements::Array
    using Refinements::Pathname

    def self.add start_index:, old_lines:, new_lines:
      computed_new_lines = start_index.zero? ? new_lines : new_lines + "\n"
      old_lines.insert start_index, *computed_new_lines
    end

    def self.remove start_index, finish_index, lines
      range = (start_index - 1)..finish_index
      lines.reject.with_index { |_, index| range.include? index }
    end

    def initialize builder: Builder.new
      @builder = builder
    end

    def call path, label: Container[:configuration].label
      path.rewrite do |body|
        lines = body.each_line.to_a
        builder.prependable?(lines) ? prepend(lines, label) : replace(lines, label)
      end
    end

    private

    attr_reader :builder

    def replace lines, label
      start_index = builder.start_index lines
      finish_index = builder.finish_index lines
      klass = self.class

      klass.add(
        start_index:,
        old_lines: klass.remove(start_index, finish_index, lines),
        new_lines: new_lines(lines, label, finish_index)
      ).join
    end

    def new_lines lines, label, finish_index
      if builder.unbuildable? lines
        builder.comments
      else
        content lines[finish_index, lines.length], label
      end
    end

    def prepend(lines, label) = [content(lines, label), lines.join].compress.join("\n")

    def content(lines, label) = builder.call(lines, label:)
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
tocer-17.5.0 lib/tocer/writer.rb
tocer-17.3.0 lib/tocer/writer.rb
tocer-17.2.0 lib/tocer/writer.rb
tocer-17.1.0 lib/tocer/writer.rb
tocer-17.0.0 lib/tocer/writer.rb