Module: Decant::Frontmatter

Defined in:
lib/decant/frontmatter.rb

Class Method Summary collapse

Class Method Details

.load(input) ⇒ Array([Hash<Symbol, anything>, nil], String)

Parse a String input (the contents of a file) into its frontmatter / content constituents.

For frontmatter to be valid/detected the input must start with a line consisting of three dashes ---, then the YAML, then another line of three dashes. The returned Hash will have Symbol keys.

Technically frontmatter can be any valid YAML not just key/value pairs but this would be very unusual and wouldn’t be compatible with other frontmatter-related expectations like Content.frontmatter.

Examples:

Input with valid frontmatter

---
title: Frontmatter
---
The rest of the content

Result of loading the above input

Decant::Frontmatter.load(string)
# => [{:title=>"Frontmatter"}, "The rest of the content"]

Parameters:

  • input (String)

Returns:

  • (Array([Hash<Symbol, anything>, nil], String))

    a frontmatter / content tuple. If input contains frontmatter then the YAML will be parsed into a Hash with Symbol keys, if it doesn’t have frontmatter then it will be nil.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/decant/frontmatter.rb', line 34

def self.load(input)
  return [nil, input] unless input.start_with?("---\n")

  scanner = StringScanner.new(input)
  scanner.skip("---\n")
  scanner.skip_until(/^---$\n?/)
  yaml = scanner.pre_match

  return [nil, input] unless yaml

  [
    YAML.safe_load(yaml, symbolize_names: true) || {},
    scanner.post_match
  ]
end