Skip to content

Commit 736da42

Browse files
authored
feat: data extension (#24)
allows reading from yaml files
1 parent 4d67147 commit 736da42

File tree

4 files changed

+73
-5
lines changed

4 files changed

+73
-5
lines changed
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
defmodule Tableau.DataExtension.Config do
2+
import Schematic
3+
4+
defstruct enabled: true, dir: "_data"
5+
6+
def new(input), do: unify(schematic(), input)
7+
8+
def schematic do
9+
schema(
10+
__MODULE__,
11+
%{
12+
optional(:enabled) => bool(),
13+
optional(:dir) => str()
14+
},
15+
convert: false
16+
)
17+
end
18+
end
19+
20+
defmodule Tableau.DataExtension do
21+
use Tableau.Extension, key: :data, type: :pre_build, priority: 200
22+
23+
def run(token) do
24+
data =
25+
for file <- Path.wildcard(Path.join(token.data.dir, "**/*.{yml,yaml}")), into: %{} do
26+
key =
27+
file
28+
|> Path.basename(".yaml")
29+
|> Path.basename(".yml")
30+
31+
{key, YamlElixir.read_from_file!(file)}
32+
end
33+
34+
{:ok, Map.put(token, :data, data)}
35+
end
36+
end

lib/tableau/extensions/post_extension.ex

+3-5
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,9 @@ defmodule Tableau.PostExtension.Config do
1919
end
2020

2121
defmodule Tableau.PostExtension.Posts.Post do
22-
{:ok, config} = Tableau.Config.new(Map.new(Application.compile_env(:tableau, :config, %{})))
23-
24-
@config config
25-
2622
def build(filename, attrs, body) do
23+
{:ok, config} = Tableau.Config.new(Map.new(Application.get_env(:tableau, :config, %{})))
24+
2725
attrs
2826
|> Map.put(:body, body)
2927
|> Map.put(:file, filename)
@@ -32,7 +30,7 @@ defmodule Tableau.PostExtension.Posts.Post do
3230
:date,
3331
DateTime.from_naive!(
3432
Code.eval_string(attrs.date) |> elem(0),
35-
@config.timezone
33+
config.timezone
3634
)
3735
)
3836
|> Map.put(

test/support/fixtures/movies.yaml

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
movies:
2+
- name: Back to the Future
3+
- name: Spider-Man 2
4+
- name: Titanic
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
defmodule Tableau.DataExtensionTest do
2+
use ExUnit.Case, async: true
3+
4+
alias Tableau.DataExtension
5+
6+
test "reads files from disk" do
7+
token = %{data: %{dir: "test/support/fixtures"}}
8+
9+
assert {:ok, actual} = DataExtension.run(token)
10+
11+
assert actual == %{
12+
data: %{
13+
"books" => %{
14+
"books" => [
15+
%{"author" => "Michael Crichton", "name" => "Jurassic Park"},
16+
%{"author" => "JRR Tolkien", "name" => "Lord of the Rings"},
17+
%{"author" => "Blake Crouch", "name" => "Dark Matter"}
18+
]
19+
},
20+
"movies" => %{
21+
"movies" => [
22+
%{"name" => "Back to the Future"},
23+
%{"name" => "Spider-Man 2"},
24+
%{"name" => "Titanic"}
25+
]
26+
}
27+
}
28+
}
29+
end
30+
end

0 commit comments

Comments
 (0)