Sha256: c124fc33f83d7c347f212c64adf5036cc1e42f14aa225fd0ab565ee89755a058

Contents?: true

Size: 1.15 KB

Versions: 15

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

require "refinements/arrays"

module Tocer
  module Transformers
    # Transforms a Markdown header (embedded link) into a table of contents link.
    class Link
      using Refinements::Arrays

      def initialize text, parser: Parsers::Header
        @parser = parser.new text
      end

      def label
        parser.content.gsub embedded_link, embedded_link_label
      end

      def url
        label.downcase.gsub(/\s/, "-").gsub(/[^\w\-]+/, "")
      end

      def call url_suffix: ""
        "#{indented_bullet}[#{label}](##{computed_url url_suffix})"
      end

      private

      attr_reader :parser

      def computed_url suffix = ""
        [url, suffix.to_s].compress.join "-"
      end

      def embedded_link
        "[#{embedded_link_label}](#{embedded_link_url})"
      end

      def embedded_link_label
        parser.content[/\[(.*)\]/, 1]
      end

      def embedded_link_url
        parser.content[/\((.*)\)/, 1]
      end

      def indented_bullet
        prefix_to_spaces.gsub(/\s{2}$/, "- ")
      end

      def prefix_to_spaces
        Array.new(parser.prefix.length, "  ").join
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
tocer-11.1.0 lib/tocer/transformers/link.rb
tocer-11.0.0 lib/tocer/transformers/link.rb
tocer-10.5.0 lib/tocer/transformers/link.rb
tocer-10.4.1 lib/tocer/transformers/link.rb
tocer-10.4.0 lib/tocer/transformers/link.rb
tocer-10.3.0 lib/tocer/transformers/link.rb
tocer-10.2.0 lib/tocer/transformers/link.rb
tocer-10.1.1 lib/tocer/transformers/link.rb
tocer-10.1.0 lib/tocer/transformers/link.rb
tocer-10.0.1 lib/tocer/transformers/link.rb
tocer-10.0.0 lib/tocer/transformers/link.rb
tocer-9.1.2 lib/tocer/transformers/link.rb
tocer-9.1.1 lib/tocer/transformers/link.rb
tocer-9.1.0 lib/tocer/transformers/link.rb
tocer-9.0.0 lib/tocer/transformers/link.rb