Use prefixes of the graphs of a RDF.Dataset when serializing to Turtle

This commit is contained in:
Marcel Otto 2020-09-14 16:41:41 +02:00
parent 6e9889c1bd
commit 081a78c692
3 changed files with 99 additions and 0 deletions

View file

@ -16,6 +16,11 @@ This project adheres to [Semantic Versioning](http://semver.org/) and
- the most common conflict resolution strategies on `RDF.PrefixMap.merge/3` can now
be chosen directly with the atoms `:ignore` and `:overwrite`
### Changed
- when serializing a `RDF.Dataset` with the Turtle encoder the prefixes of all of its graphs
are used
### Fixed
- adding an empty `RDF.Description` with a subject to an empty `RDF.Graph` resulted in

View file

@ -92,6 +92,26 @@ defmodule RDF.Turtle.Encoder do
end
defp prefixes(nil, %RDF.Graph{prefixes: prefixes}) when not is_nil(prefixes), do: prefixes
defp prefixes(nil, %RDF.Dataset{} = dataset) do
prefixes =
dataset
|> RDF.Dataset.graphs()
|> Enum.reduce(RDF.PrefixMap.new(), fn graph, prefixes ->
if graph.prefixes do
RDF.PrefixMap.merge!(prefixes, graph.prefixes, :ignore)
else
prefixes
end
end)
if Enum.empty?(prefixes) do
RDF.default_prefixes()
else
prefixes
end
end
defp prefixes(nil, _), do: RDF.default_prefixes()
defp prefixes(prefixes, _), do: RDF.PrefixMap.new(prefixes)

View file

@ -289,6 +289,80 @@ defmodule RDF.Turtle.EncoderTest do
end
end
describe "serializing a dataset" do
test "prefixes of the graphs are merged properly" do
dataset =
RDF.Dataset.new()
|> RDF.Dataset.add(
Graph.new(
[
{EX.__base_iri__(), RDF.type(), OWL.Ontology},
{EX.S1, RDF.type(), EX.O}
],
base_iri: EX.__base_iri__(),
prefixes: %{
rdf: RDF,
owl: OWL
}
)
)
|> RDF.Dataset.add(
Graph.new(
{EX.S3, EX.p(), EX.O},
name: EX.Graph1,
prefixes: %{
ex: EX,
rdf: RDF
}
)
)
|> RDF.Dataset.add(
Graph.new(
{~I<http://other.example.com/S2>, RDF.type(), RDFS.Class},
name: EX.Graph2,
prefixes: %{
ex: "http://other.example.com/",
rdf: RDF,
rdfs: RDFS
}
)
)
assert Turtle.Encoder.encode!(dataset) ==
"""
@prefix ex: <http://example.org/#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
<http://other.example.com/S2>
a rdfs:Class .
ex:
a owl:Ontology .
ex:S1
a ex:O .
ex:S3
ex:p ex:O .
"""
end
test "when none of the graphs uses prefixes the default prefixes are used" do
assert RDF.Dataset.new({EX.S, EX.p(), EX.O})
|> Turtle.Encoder.encode!() ==
"""
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://example.org/#S>
<http://example.org/#p> <http://example.org/#O> .
"""
end
end
describe "prefixed_name/2" do
setup do
{:ok,