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
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 |
# File 'lib/ruby_rich/markdown.rb', line 1214 def self.extract(markdown_text) # Strip leading blank lines so that a heredoc like <<~'MD'\n\n---\n # is still recognised as having frontmatter. stripped = markdown_text.lstrip return [markdown_text, nil, false] unless stripped.start_with?("---") rest = stripped[3..] offset = 3 rest.each_line do |line| trimmed = line.strip if trimmed == "---" || trimmed == "..." fm_block = stripped[3...offset] content = stripped[(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
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 |
# File 'lib/ruby_rich/markdown.rb', line 1237 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 with explicit indicator i += 1 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? # Empty value: could be a list or an implicit multiline string. i += 1 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
1280 1281 1282 |
# File 'lib/ruby_rich/markdown.rb', line 1280 def self.unquote(s) (s.length >= 2 && ((s.start_with?('"') && s.end_with?('"')) || (s.start_with?("'") && s.end_with?("'")))) ? s[1...-1] : s end |