Add RDF.Namespace.namespace?/1

This commit is contained in:
Marcel Otto 2022-06-06 20:05:38 +02:00
parent 26eb6681cc
commit 78ff120732
2 changed files with 32 additions and 10 deletions

View file

@ -79,9 +79,8 @@ defmodule RDF.Namespace do
"""
@spec resolve_term!(IRI.t() | module) :: IRI.t()
def resolve_term!(expr) do
with {:ok, iri} <- resolve_term(expr) do
iri
else
case resolve_term(expr) do
{:ok, iri} -> iri
{:error, error} -> raise error
end
end
@ -112,16 +111,19 @@ defmodule RDF.Namespace do
end
defp do_resolve_term(namespace, term) do
is_module =
case Code.ensure_compiled(namespace) do
{:module, _} -> true
_ -> false
end
if is_module and Keyword.has_key?(namespace.__info__(:functions), :__resolve_term__) do
if namespace?(namespace) do
namespace.__resolve_term__(term)
else
{:error, %RDF.Namespace.UndefinedTermError{message: "#{namespace} is not a RDF.Namespace"}}
end
end
@doc false
@spec namespace?(module) :: boolean
def namespace?(name) do
case Code.ensure_compiled(name) do
{:module, name} -> function_exported?(name, :__resolve_term__, 1)
_ -> false
end
end
end

View file

@ -91,4 +91,24 @@ defmodule RDF.NamespaceTest do
~I<http://example.com/foo>
]
end
describe "namespace?/1" do
test "with RDF.Namespace modules" do
assert RDF.Namespace.namespace?(RDF.TestNamespaces.SimpleNS) == true
assert RDF.Namespace.namespace?(RDF.TestNamespaces.NSfromPropertyMap) == true
end
test "with RDF.Vocabulary.Namespace modules" do
assert RDF.Namespace.namespace?(EX) == true
assert RDF.Namespace.namespace?(RDF.NS.RDF) == true
assert RDF.Namespace.namespace?(RDF.NS.RDFS) == true
assert RDF.Namespace.namespace?(RDF.NS.OWL) == true
assert RDF.Namespace.namespace?(RDF.NS.XSD) == true
end
test "with non-RDF.Namespace modules" do
assert RDF.Namespace.namespace?(Enum) == false
assert RDF.Namespace.namespace?(__MODULE__) == false
end
end
end