rdf-ex/lib/rdf/serializations/ntriples_encoder.ex

50 lines
1.1 KiB
Elixir
Raw Normal View History

2017-05-19 16:11:58 +00:00
defmodule RDF.NTriples.Encoder do
@moduledoc false
2017-05-19 16:11:58 +00:00
use RDF.Serialization.Encoder
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
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