2017-05-19 16:11:58 +00:00
|
|
|
defmodule RDF.NTriples.Encoder do
|
2017-06-16 16:45:30 +00:00
|
|
|
@moduledoc false
|
|
|
|
|
2017-05-19 16:11:58 +00:00
|
|
|
use RDF.Serialization.Encoder
|
|
|
|
|
2017-08-20 20:35:14 +00:00
|
|
|
alias RDF.{IRI, Literal, BlankNode}
|
2017-05-19 16:11:58 +00:00
|
|
|
|
|
|
|
@xsd_string RDF.Datatype.NS.XSD.string
|
|
|
|
|
2018-03-02 00:14:50 +00:00
|
|
|
def encode(data, _opts \\ []) do
|
2017-05-19 16:11:58 +00:00
|
|
|
result =
|
|
|
|
data
|
|
|
|
|> Enum.reduce([], fn (statement, result) ->
|
|
|
|
[statement(statement) | result]
|
|
|
|
end)
|
|
|
|
|> Enum.reverse
|
|
|
|
|> Enum.join("\n")
|
|
|
|
{:ok, (if result == "", do: result, else: result <> "\n")}
|
|
|
|
end
|
|
|
|
|
|
|
|
def statement({subject, predicate, object}) do
|
|
|
|
"#{term(subject)} #{term(predicate)} #{term(object)} ."
|
|
|
|
end
|
|
|
|
|
2017-08-20 20:35:14 +00:00
|
|
|
def term(%IRI{} = iri) do
|
|
|
|
"<#{to_string(iri)}>"
|
2017-05-19 16:11:58 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def term(%Literal{value: value, language: language}) when not is_nil(language) do
|
|
|
|
~s["#{value}"@#{language}]
|
|
|
|
end
|
|
|
|
|
|
|
|
def term(%Literal{value: value, language: language}) when not is_nil(language) do
|
|
|
|
~s["#{value}"@#{language}]
|
|
|
|
end
|
|
|
|
|
|
|
|
def term(%Literal{datatype: @xsd_string} = literal) do
|
|
|
|
~s["#{Literal.lexical(literal)}"]
|
|
|
|
end
|
|
|
|
|
|
|
|
def term(%Literal{datatype: datatype} = literal) do
|
|
|
|
~s["#{Literal.lexical(literal)}"^^<#{to_string(datatype)}>]
|
|
|
|
end
|
|
|
|
|
|
|
|
def term(%BlankNode{} = bnode) do
|
|
|
|
to_string(bnode)
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|