Allow RDF.Vocabulary.Namespace modules as base

This commit is contained in:
Marcel Otto 2022-04-23 00:58:25 +02:00
parent 53631c6425
commit 363309a739
3 changed files with 43 additions and 21 deletions

View file

@ -16,6 +16,7 @@ This project adheres to [Semantic Versioning](http://semver.org/) and
- context maps can be given now with atom keys or as `RDF.PropertyMap` to
`JSON.LD.context/2` and `JSON.LD.compact/3`
- `RDF.Vocabulary.Namespace` modules can be set as base IRI
[Compare v0.3.4...HEAD](https://github.com/rdf-elixir/jsonld-ex/compare/v0.3.4...HEAD)

View file

@ -5,6 +5,8 @@ defmodule JSON.LD.Options do
as specified at <https://www.w3.org/TR/json-ld-api/#the-jsonldoptions-type>
"""
alias RDF.IRI
@type t :: %__MODULE__{
base: String.t() | nil,
compact_arrays: boolean,
@ -32,5 +34,14 @@ defmodule JSON.LD.Options do
@spec new(convertible) :: t
def new(%__MODULE__{} = options), do: options
def new(options), do: struct(__MODULE__, options)
def new(options) do
struct(__MODULE__, options)
|> set_base(options[:base])
end
@spec set_base(t, IRI.coercible()) :: t
def set_base(%__MODULE__{} = options, base) do
%__MODULE__{options | base: base && base |> IRI.coerce_base() |> to_string()}
end
end

View file

@ -683,32 +683,42 @@ defmodule JSON.LD.EncoderTest do
"familyName" => "http://schema.org/familyName"
}
expected_result =
"""
{
"@context": {
"familyName": "http://schema.org/familyName",
"givenName": "http://schema.org/givenName"
},
"@id": "http://manu.sporny.org/about#manu",
"familyName": "Sporny",
"givenName": "Manu",
"http://example.com/bar": {
"@id": "Bar"
},
"http://example.com/foo": 3.14,
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type": {
"@id": "http://schema.org/Person"
}
}
"""
|> String.trim()
assert JSON.LD.Encoder.encode!(graph,
context: context,
base: EX.__base_iri__(),
use_native_types: true,
use_rdf_type: true,
pretty: true
) ==
"""
{
"@context": {
"familyName": "http://schema.org/familyName",
"givenName": "http://schema.org/givenName"
},
"@id": "http://manu.sporny.org/about#manu",
"familyName": "Sporny",
"givenName": "Manu",
"http://example.com/bar": {
"@id": "Bar"
},
"http://example.com/foo": 3.14,
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type": {
"@id": "http://schema.org/Person"
}
}
"""
|> String.trim()
) == expected_result
assert JSON.LD.Encoder.encode!(graph,
context: context,
base: EX,
use_native_types: true,
use_rdf_type: true,
pretty: true
) == expected_result
end
end