Class: Bridgetown::FrontMatter::Loaders::YAML

Inherits:
Base
  • Object
show all
Defined in:
bridgetown-core/lib/bridgetown-core/front_matter/loaders/yaml.rb

Overview

Reads YAML-formatted front matter delineated by triple hyphens

As an example, this resource loads to the hash {"published": false, "title": "My post"}.

---
published: false
title: My post
---

Constant Summary collapse

HEADER =
%r!\A---\s*\n!
BLOCK =
%r!\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)!m

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Bridgetown::FrontMatter::Loaders::Base

Class Method Details

.header?(file) ⇒ Boolean

Determines whether a given file has YAML front matter

Parameters:

  • file (String)

    the path to the file

Returns:

  • (Boolean)

    true if the file has YAML front matter, false otherwise



25
26
27
# File 'bridgetown-core/lib/bridgetown-core/front_matter/loaders/yaml.rb', line 25

def self.header?(file)
  File.open(file, "rb", &:gets)&.match?(HEADER) || false
end

Instance Method Details

#read(file_contents) ⇒ Object

See Also:

  • Bridgetown::FrontMatter::Loaders::YAML.{Base{Base#read}


30
31
32
33
34
35
36
37
38
# File 'bridgetown-core/lib/bridgetown-core/front_matter/loaders/yaml.rb', line 30

def read(file_contents, **)
  yaml_content = file_contents.match(BLOCK) or return

  Result.new(
    content: yaml_content.post_match,
    front_matter: YAMLParser.load(yaml_content[1]),
    line_count: yaml_content[1].lines.size - 1
  )
end