separate front matter parsing

This commit is contained in:
sloane 2024-02-24 08:03:18 -05:00
parent 38f8208a44
commit 9e7c608303
2 changed files with 59 additions and 0 deletions

View file

@ -0,0 +1,17 @@
defmodule SloaneSH.FrontMatter do
@moduledoc """
Parses TOML front matter out put files
"""
def parse("+++" <> rest, _ctx) do
[toml, body] = String.split(rest, ["+++\n", "+++\r\n"], parts: 2)
with {:ok, attrs} <- Toml.decode(toml, keys: :atoms) do
{:ok, attrs, body}
end
end
def parse(body, _ctx) do
{:ok, %{}, body}
end
end

View file

@ -0,0 +1,42 @@
defmodule SloaneSH.FrontMatterTest do
use ExUnit.Case
alias SloaneSH.FrontMatter
test "parses TOML front matter" do
document = ~S"""
+++
foo = "bar"
+++
# Hello, World!
This is a document with front matter.
"""
assert {:ok, %{foo: "bar"}, "# Hello, World!" <> _} = FrontMatter.parse(document, %{})
end
test "returns an empty map is the document doesn't have front matter" do
document = ~S"""
# Hello, World!
This is a document with front matter.
"""
assert {:ok, %{} = map, document} = FrontMatter.parse(document, %{})
assert %{} = map
end
test "errors in TOML front matter produce an error" do
document = ~S"""
+++
foo = "bar
+++
# Hello, World!
This is a document with front matter.
"""
assert {:error, _} = FrontMatter.parse(document, %{})
end
end