separate front matter parsing
This commit is contained in:
parent
38f8208a44
commit
9e7c608303
2 changed files with 59 additions and 0 deletions
17
lib/sloane_sh/front_matter.ex
Normal file
17
lib/sloane_sh/front_matter.ex
Normal 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
|
42
test/sloane_sh/front_matter_test.exs
Normal file
42
test/sloane_sh/front_matter_test.exs
Normal 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
|
Loading…
Reference in a new issue