Refactor code to comply with credo suggestions
[akkoma] / lib / xml_builder.ex
1 defmodule Pleroma.XmlBuilder do
2 def to_xml({tag, attributes, content}) do
3 open_tag = make_open_tag(tag, attributes)
4
5 content_xml = to_xml(content)
6
7 "<#{open_tag}>#{content_xml}</#{tag}>"
8 end
9
10 def to_xml({tag, %{} = attributes}) do
11 open_tag = make_open_tag(tag, attributes)
12
13 "<#{open_tag} />"
14 end
15
16 def to_xml({tag, content}), do: to_xml({tag, %{}, content})
17
18 def to_xml(content) when is_binary(content) do
19 to_string(content)
20 end
21
22 def to_xml(content) when is_list(content) do
23 for element <- content do
24 to_xml(element)
25 end
26 |> Enum.join
27 end
28
29 def to_xml(%NaiveDateTime{} = time) do
30 NaiveDateTime.to_iso8601(time)
31 end
32
33 def to_doc(content), do: ~s(<?xml version="1.0" encoding="UTF-8"?>) <> to_xml(content)
34
35 defp make_open_tag(tag, attributes) do
36 attributes_string = for {attribute, value} <- attributes do
37 "#{attribute}=\"#{value}\""
38 end |> Enum.join(" ")
39
40 [tag, attributes_string] |> Enum.join(" ") |> String.strip
41 end
42 end