diff --git a/CHANGELOG.md b/CHANGELOG.md index a5e2939..4520603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ This project adheres to [Semantic Versioning](http://semver.org/) and [Keep a CHANGELOG](http://keepachangelog.com). +## Unreleased + +### Added + +- `RDF.PrefixMap.put/3` for adding a prefix mapping and overwrite an existing one + +### Changed + +- more compact Inspect form for `RDF.PrefixMap` + + +[Compare v0.9.0...HEAD](https://github.com/rdf-elixir/rdf-ex/compare/v0.9.0...HEAD) + + + ## 0.9.0 - 2020-10-13 The API of the all three RDF datastructures `RDF.Dataset`, `RDF.Graph` and diff --git a/lib/rdf/prefix_map.ex b/lib/rdf/prefix_map.ex index e786a32..3ca19a1 100644 --- a/lib/rdf/prefix_map.ex +++ b/lib/rdf/prefix_map.ex @@ -97,6 +97,22 @@ defmodule RDF.PrefixMap do end end + @doc """ + Adds a prefix mapping to `prefix_map` overwriting an existing mapping. + """ + @spec put(t, coercible_prefix, coercible_namespace) :: t + def put(prefix_map, prefix, namespace) + + def put(%__MODULE__{map: map}, prefix, %IRI{} = namespace) when is_atom(prefix) do + %__MODULE__{map: Map.put(map, prefix, namespace)} + end + + def put(%__MODULE__{} = prefix_map, prefix, namespace) do + with {prefix, namespace} = normalize({prefix, namespace}) do + put(prefix_map, prefix, namespace) + end + end + @doc """ Merges two `RDF.PrefixMap`s. diff --git a/test/unit/prefix_map_test.exs b/test/unit/prefix_map_test.exs index 5843c4d..70400df 100644 --- a/test/unit/prefix_map_test.exs +++ b/test/unit/prefix_map_test.exs @@ -115,6 +115,40 @@ defmodule RDF.PrefixMapTest do end end + describe "put/3" do + test "when no mapping of the given prefix exists" do + assert PrefixMap.put(@example1, :ex2, @ex_ns2) == @example2 + end + + test "when the prefix is given as a string" do + assert PrefixMap.put(@example1, "ex2", @ex_ns2) == @example2 + end + + test "when the IRI namespace is given as a string" do + assert PrefixMap.put(@example1, :ex2, "http://example.com/bar#") == @example2 + end + + test "when the IRI namespace is given as a RDF.Vocabulary.Namespace" do + assert PrefixMap.put(@example1, :ex, EX) == @example4 + end + + test "when the IRI namespace is given as a RDF.Vocabulary.Namespace which is not loaded yet" do + assert prefix_map = PrefixMap.new() |> PrefixMap.put(:rdfs, RDF.NS.RDFS) + assert PrefixMap.has_prefix?(prefix_map, :rdfs) + end + + test "when the IRI namespace is given as an atom" do + assert_raise RDF.Namespace.UndefinedTermError, "foo is not a term on a RDF.Namespace", fn -> + PrefixMap.put(@example1, :ex, :foo) + end + end + + test "when a mapping of the given prefix to a different namespace already exists" do + assert PrefixMap.put(@example1, :ex1, "http://example.com/bar#") == + PrefixMap.new(ex1: "http://example.com/bar#") + end + end + describe "merge/2" do test "when the prefix maps are disjunctive" do other_prefix_map = PrefixMap.new(ex3: @ex_ns3)