Class: Textus::Entry::Markdown

Inherits:
Base
  • Object
show all
Defined in:
lib/textus/entry/markdown.rb

Overview

Markdown with YAML frontmatter. Original Entry implementation.

Class Method Summary collapse

Methods inherited from Base

validate_against

Class Method Details

.extensionsObject



36
# File 'lib/textus/entry/markdown.rb', line 36

def self.extensions = [".md"]

.parse(raw, path: nil) ⇒ Object

Raises:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/textus/entry/markdown.rb', line 7

def self.parse(raw, path: nil)
  raw = raw.dup.force_encoding(Encoding::UTF_8)
  raise BadFrontmatter.new(path, "entry is not valid UTF-8") unless raw.valid_encoding?
  return { "_meta" => {}, "body" => raw, "content" => nil } unless raw.start_with?("---\n") || raw.start_with?("---\r\n")

  lines = raw.split(/\r?\n/, -1)
  close_idx = lines[1..].index("---")
  raise BadFrontmatter.new(path, "frontmatter not terminated") unless close_idx

  close_idx += 1
  fm_yaml = lines[1...close_idx].join("\n")
  body = lines[(close_idx + 1)..].join("\n")
  begin
    fm = fm_yaml.strip.empty? ? {} : ::YAML.safe_load(fm_yaml, permitted_classes: [Date, Time], aliases: false)
  rescue Psych::SyntaxError => e
    raise BadFrontmatter.new(path, "YAML parse failed: #{e.message}")
  end
  fm = {} unless fm.is_a?(Hash)
  { "_meta" => fm, "body" => body, "content" => nil }
end

.serialize(meta:, body:, content: nil) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/textus/entry/markdown.rb', line 28

def self.serialize(meta:, body:, content: nil)
  _ = content # markdown ignores content
  fm_yaml = meta.empty? ? "" : ::YAML.dump(meta).sub(/\A---\n/, "")
  body = body.to_s
  body += "\n" unless body.empty? || body.end_with?("\n")
  "---\n#{fm_yaml}---\n#{body}"
end