diff --git a/CHANGELOG.md b/CHANGELOG.md index 881bfd5..0f34152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ This project adheres to [Semantic Versioning](http://semver.org/) and ### Changed - `RDF.Turtle.Decoder` saves the base IRI now +- `RDF.Turtle.Encoder` now takes the base IRI to be serialized from the graph when + no base IRI is given with the `base` option [Compare v0.6.1...HEAD](https://github.com/marcelotto/rdf-ex/compare/v0.6.1...HEAD) diff --git a/lib/rdf/serializations/turtle_encoder.ex b/lib/rdf/serializations/turtle_encoder.ex index ee81a02..f7e7d8e 100644 --- a/lib/rdf/serializations/turtle_encoder.ex +++ b/lib/rdf/serializations/turtle_encoder.ex @@ -28,7 +28,7 @@ defmodule RDF.Turtle.Encoder do @impl RDF.Serialization.Encoder def encode(data, opts \\ []) do - with base = Keyword.get(opts, :base) |> init_base(), + with base = Keyword.get(opts, :base) |> base_iri(data) |> init_base(), prefixes = Keyword.get(opts, :prefixes) |> prefixes(data) |> init_prefixes(), {:ok, state} = State.start_link(data, base, prefixes) do try do @@ -45,6 +45,9 @@ defmodule RDF.Turtle.Encoder do end end + defp base_iri(nil, %RDF.Graph{base_iri: base_iri}), do: base_iri + defp base_iri(base_iri, _), do: RDF.iri(base_iri) + defp init_base(nil), do: nil defp init_base(base) do diff --git a/test/unit/turtle_encoder_test.exs b/test/unit/turtle_encoder_test.exs index fbba658..7d16a4c 100644 --- a/test/unit/turtle_encoder_test.exs +++ b/test/unit/turtle_encoder_test.exs @@ -85,6 +85,26 @@ defmodule RDF.Turtle.EncoderTest do """ end + test "when no base IRI is given, the base IRI from the given graph is used" do + assert Turtle.Encoder.encode!(Graph.new([{EX.S1, EX.p1, EX.O1}], prefixes: %{}, + base_iri: EX.__base_iri__)) == + """ + @base <#{to_string(EX.__base_iri__)}> . + + . + """ + end + + test "when a base IRI is given, it has used instead of the base IRI of the given graph" do + assert Turtle.Encoder.encode!(Graph.new([{EX.S1, EX.p1, EX.O1}], prefixes: %{}, + base_iri: EX.other), base: EX.__base_iri__) == + """ + @base <#{to_string(EX.__base_iri__)}> . + + . + """ + end + test "when no prefixes are given and no prefixes are in the given graph the default_prefixes are used" do assert Turtle.Encoder.encode!(Graph.new({EX.S, EX.p, XSD.string})) == """