Class: Coelacanth::Extractor::MarkdownListingCollector

Inherits:
Object
  • Object
show all
Defined in:
lib/coelacanth/extractor/markdown_listing_collector.rb

Overview

Extracts structured listings from Markdown content.

Constant Summary collapse

LIST_ITEM_PATTERN =
/\A(?:[-*+]|\d+\.)\s+/.freeze
HEADING_PATTERN =
/\A#+\s*/.freeze
MIN_ITEMS =
3
MIN_TITLE_LENGTH =
2

Instance Method Summary collapse

Instance Method Details

#call(markdown:, base_url: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/coelacanth/extractor/markdown_listing_collector.rb', line 14

def call(markdown:, base_url: nil)
  return [] if markdown.to_s.strip.empty?

  listings = []
  current = nil
  pending_heading = nil

  finalize_current = lambda do
    next unless current

    if current[:items].length >= MIN_ITEMS
      listings << { heading: current[:heading], items: current[:items] }
    end

    current = nil
  end

  markdown.each_line do |line|
    stripped = line.strip

    if stripped.empty?
      finalize_current.call
      next
    end

    if heading_line?(stripped)
      finalize_current.call
      pending_heading = normalize_heading(stripped)
      next
    end

    if list_item_line?(stripped)
      current ||= { heading: pending_heading, items: [] }
      pending_heading = nil

      if (item = build_item(stripped, base_url))
        current[:items] << item
      end
    else
      finalize_current.call
      pending_heading = nil
    end
  end

  finalize_current.call

  listings
end