Skip to content

Instantly share code, notes, and snippets.

@hok
Created March 14, 2019 22:51
Show Gist options
  • Save hok/5ad155203e5261e60d4f0ce0fa9d9e4b to your computer and use it in GitHub Desktop.
Save hok/5ad155203e5261e60d4f0ce0fa9d9e4b to your computer and use it in GitHub Desktop.
defmodule Feed.S3.Sync.Post do
defstruct title: "",
summary: "",
content: "",
filename: "",
author: "",
cover_image: "",
tags: [],
published_at: "",
published: false
alias __MODULE__
@options %Earmark.Options{code_class_prefix: "language-"}
def compile(file) do
file
|> split()
|> extract()
end
defp split(data) do
[frontmatter, markdown] = String.split(data, ~r/\n-{3,}\n/, parts: 2)
{parse_yaml(frontmatter), Earmark.as_html!(markdown, @options)}
end
defp parse_yaml(yaml) do
[parsed] = :yamerl_constr.string(yaml)
parsed
end
defp extract({props, content}) do
%Post{
title: get_prop(props, "title"),
summary: get_prop(props, "summary"),
author: get_prop(props, "author"),
content: content,
cover_image: get_prop(props, "image"),
tags: get_prop(props, "tags"),
published_at: get_date_prop(props, "date"),
published: get_boolean_prop(props, "published")
}
end
defp get_prop(props, key) do
parse_value(props, key)
end
def get_date_prop(props, field) do
props
|> get_prop(field)
|> Timex.parse!("%Y-%m-%d %H:%M:%S", :strftime)
end
def get_boolean_prop(props, field) do
props
|> get_prop(field)
|> convert_to_boolean()
end
defp parse_value(props, "tags") do
case get_value(props, "tags") do
:undefined -> nil
list ->
Enum.map(list, fn item -> to_string(item) end)
end
end
defp parse_value(props, key) do
case get_value(props, key) do
:undefined -> nil
x ->
to_string(x)
end
end
defp get_value(props, key) do
:proplists.get_value(String.to_charlist(key), props)
end
def convert_to_boolean("true"), do: true
def convert_to_boolean("false"), do: false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment