Module: RubyRich::Markdown::Frontmatter

Defined in:
lib/ruby_rich/markdown.rb

Overview

—- Frontmatter extraction —- Extracts YAML-style frontmatter (delimited by —) and returns [content_without_fm, parsed_pairs, is_vertical].

Constant Summary collapse

VERTICAL_THRESHOLD =
5

Class Method Summary collapse

Class Method Details

.extract(markdown_text) ⇒ Object



949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/ruby_rich/markdown.rb', line 949

def self.extract(markdown_text)
  return [markdown_text, nil, false] unless markdown_text.start_with?("---\n")

  rest = markdown_text[4..]
  offset = 4
  rest.each_line do |line|
    if line == "---\n" || line == "...\n" || line == "---" || line == "..."
      fm_block = markdown_text[4...offset]
      content = markdown_text[(offset + line.length)..] || ""
      pairs = parse_pairs(fm_block)
      return [markdown_text, nil, false] if pairs.empty?
      vertical = pairs.length >= VERTICAL_THRESHOLD
      return [content, pairs, vertical]
    end
    offset += line.length
  end
  [markdown_text, nil, false]
end

.parse_pairs(block) ⇒ Object



968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/ruby_rich/markdown.rb', line 968

def self.parse_pairs(block)
  pairs = []
  lines = block.lines.map(&:chomp)
  i = 0
  while i < lines.length
    trimmed = lines[i].strip
    i += 1 and next if trimmed.empty? || trimmed.start_with?('#')

    colon_pos = trimmed.index(':')
    i += 1 and next unless colon_pos

    key = trimmed[0...colon_pos].strip
    raw_value = trimmed[(colon_pos + 1)..].strip
    i += 1 and next if key.empty?

    if ["", ">-", ">", "|", "|-"].include?(raw_value)
      # Multiline value
      parts = []
      while i < lines.length && lines[i].start_with?(' ', "\t")
        part = lines[i].strip
        parts << part unless part.empty?
        i += 1
      end
      pairs << [key, parts.join(" ")]
    elsif raw_value.empty?
      # List value (indented items)
      items = []
      while i < lines.length && lines[i].start_with?(' ', "\t")
        item = lines[i].strip
        items << (item.start_with?("- ") ? item[2..].strip : item)
        i += 1
      end
      pairs << [key, items.empty? ? "" : items.join(", ")]
    else
      pairs << [key, unquote(raw_value)]
      i += 1
    end
  end
  pairs
end

.unquote(s) ⇒ Object



1009
1010
1011
# File 'lib/ruby_rich/markdown.rb', line 1009

def self.unquote(s)
  (s.length >= 2 && ((s.start_with?('"') && s.end_with?('"')) || (s.start_with?("'") && s.end_with?("'")))) ? s[1...-1] : s
end