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

View file

@ -91,4 +91,24 @@ defmodule RDF.NamespaceTest do
~I<http://example.com/foo> ~I<http://example.com/foo>
] ]
end 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 end