Module: Sourcerer::YamlFrontmatter
- Defined in:
- lib/sourcerer/yaml_frontmatter.rb
Overview
Single owner of YAML frontmatter parsing across Sourcerer.
Both AsciiDoc pages (the Jekyll convention of embedding ----fenced YAML at the top of a .adoc file) and Markdown pages use the same syntax. All Sourcerer code that needs to detect, extract, or remove a frontmatter block delegates here instead of duplicating logic or constants.
Constant Summary collapse
- REGEXP =
Matches a leading
----fenced YAML block at the start of a file. Content between the fences must be non-empty (.?+, lazy). The closing fence must be followed by a newline. /\A(---\s*\n.+?\n)(---\s*\n)/m
Class Method Summary collapse
-
.extract(source_text) ⇒ Hash
Parse the YAML frontmatter from
source_textand return it as a Hash. -
.strip(source_text) ⇒ String
Return
source_textwith the leading YAML frontmatter block removed.
Class Method Details
.extract(source_text) ⇒ Hash
Parse the YAML frontmatter from source_text and return it as a Hash.
Returns an empty Hash when no frontmatter is present or when the YAML is malformed.
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/sourcerer/yaml_frontmatter.rb', line 27 def extract source_text match = source_text.match(REGEXP) return {} unless match frontmatter_payload = match[1].sub(/\A---\s*\n/, '') parsed = YAML.safe_load(frontmatter_payload, aliases: true) parsed.is_a?(Hash) ? parsed : {} rescue Psych::SyntaxError {} end |
.strip(source_text) ⇒ String
Return source_text with the leading YAML frontmatter block removed.
42 43 44 |
# File 'lib/sourcerer/yaml_frontmatter.rb', line 42 def strip source_text source_text.sub(REGEXP, '') end |