Initial commit
This commit is contained in:
20
lib/parser/base.ex
Normal file
20
lib/parser/base.ex
Normal file
@@ -0,0 +1,20 @@
|
||||
defmodule Localizator.Parser.Base do
|
||||
@typedoc """
|
||||
Text contents of the file for parse in Map
|
||||
"""
|
||||
@type contents :: String.t()
|
||||
|
||||
@typedoc """
|
||||
Data in Map format for encoding to text contents of the file
|
||||
"""
|
||||
@type data :: map
|
||||
|
||||
@typedoc """
|
||||
List of the file extensions for parser
|
||||
"""
|
||||
@type extensions :: [String.t()]
|
||||
|
||||
@callback parse(contents) :: {:ok, data} | {:error, any}
|
||||
@callback generate(data) :: {:ok, contents} | {:error, any}
|
||||
@callback extensions() :: {:ok, extensions}
|
||||
end
|
||||
25
lib/parser/json.ex
Normal file
25
lib/parser/json.ex
Normal file
@@ -0,0 +1,25 @@
|
||||
defmodule Localizator.Parser.JSON do
|
||||
@extensions ["json"]
|
||||
|
||||
@type contents :: String.t()
|
||||
@type data :: map
|
||||
@type extensions :: [String.t()]
|
||||
|
||||
@behaviour Localizator.Parser.Base
|
||||
|
||||
@impl true
|
||||
@spec parse(contents) :: {:ok, data} | {:error, atom | Jason.DecodeError.t()}
|
||||
def parse(contents) do
|
||||
Jason.decode(contents)
|
||||
end
|
||||
|
||||
@impl true
|
||||
@spec generate(data) :: {:ok, contents} | {:error, any}
|
||||
def generate(data) do
|
||||
Jason.encode(data)
|
||||
end
|
||||
|
||||
@impl true
|
||||
@spec extensions() :: {:ok, extensions}
|
||||
def extensions(), do: {:ok, @extensions}
|
||||
end
|
||||
42
lib/parser/yaml.ex
Normal file
42
lib/parser/yaml.ex
Normal file
@@ -0,0 +1,42 @@
|
||||
defmodule Localizator.Parser.YAML do
|
||||
@indent " "
|
||||
@extensions ["yml", "yaml"]
|
||||
|
||||
@type contents :: String.t()
|
||||
@type data :: map
|
||||
@type extensions :: [String.t()]
|
||||
|
||||
@behaviour Localizator.Parser.Base
|
||||
|
||||
@impl true
|
||||
@spec parse(contents) :: {:ok, data} | {:error, atom | Jason.DecodeError.t()}
|
||||
def parse(contents) do
|
||||
YamlElixir.read_from_string(contents)
|
||||
end
|
||||
|
||||
@impl true
|
||||
@spec generate(data) :: {:ok, contents} | {:error, any}
|
||||
def generate(data) do
|
||||
{:ok, to_yaml(data)}
|
||||
end
|
||||
|
||||
defp to_yaml(data, indentation \\ "") do
|
||||
data
|
||||
|> Map.keys()
|
||||
|> Enum.map(fn key ->
|
||||
Map.fetch!(data, key)
|
||||
|> value_to_yaml(key, indentation)
|
||||
end)
|
||||
|> Enum.join("\n")
|
||||
end
|
||||
|
||||
defp value_to_yaml(value, key, indentation) when is_number(value) or is_bitstring(value),
|
||||
do: "#{indentation}#{key}: #{value}"
|
||||
|
||||
defp value_to_yaml(value, key, indentation) when is_map(value),
|
||||
do: "#{indentation}#{key}:\n#{to_yaml(value, "#{indentation}#{@indent}")}"
|
||||
|
||||
@impl true
|
||||
@spec extensions() :: {:ok, extensions}
|
||||
def extensions(), do: {:ok, @extensions}
|
||||
end
|
||||
Reference in New Issue
Block a user