Module: RedQuilt::Frontmatter
- Defined in:
- lib/red_quilt/frontmatter.rb
Overview
Extracts a leading YAML frontmatter block from a Markdown source.
Class Method Summary collapse
-
.blank_out(source, offset) ⇒ Object
Replaces every character before
offsetwith a blank line for each consumed source line, keeping later line numbers intact. -
.extract(source, diagnostics: nil) ⇒ Object
Extracts frontmatter from
source, returning a two-element array: [data, body]. -
.parse_yaml(yaml, diagnostics: nil) ⇒ Object
Parses the YAML body with a restricted loader (no arbitrary object instantiation; Date / Time permitted for common frontmatter dates).
Class Method Details
.blank_out(source, offset) ⇒ Object
Replaces every character before offset with a blank line for each consumed source line, keeping later line numbers intact.
49 50 51 52 |
# File 'lib/red_quilt/frontmatter.rb', line 49 def blank_out(source, offset) consumed = source[0, offset] ("\n" * consumed.count("\n")) + source[offset..] end |
.extract(source, diagnostics: nil) ⇒ Object
Extracts frontmatter from source, returning a two-element array: [data, body]. data is the parsed Hash (or nil when there is no frontmatter), and body is the source with the frontmatter region blanked out.
diagnostics is an optional array; on a YAML syntax error a warning Diagnostic is appended and data is returned as nil.
22 23 24 25 26 27 28 29 |
# File 'lib/red_quilt/frontmatter.rb', line 22 def extract(source, diagnostics: nil) match = PATTERN.match(source) return [nil, source] unless match data = parse_yaml(match[1], diagnostics: diagnostics) body = blank_out(source, match.end(0)) [data, body] end |
.parse_yaml(yaml, diagnostics: nil) ⇒ Object
Parses the YAML body with a restricted loader (no arbitrary object instantiation; Date / Time permitted for common frontmatter dates). Returns the parsed value, or nil on a syntax error.
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/red_quilt/frontmatter.rb', line 34 def parse_yaml(yaml, diagnostics: nil) Psych.safe_load(yaml, permitted_classes: [Date, Time], aliases: false) rescue Psych::SyntaxError => e diagnostics&.push( Diagnostic.new( severity: :warning, rule: :frontmatter, message: "invalid YAML frontmatter: #{e.}", ), ) nil end |