Add RDF.Literal.Datatype.Registry.xsd_datatype/1

This commit is contained in:
Marcel Otto 2020-05-10 01:37:01 +02:00
parent d18c7ed475
commit b53d09d4f5
3 changed files with 34 additions and 3 deletions

View file

@ -25,7 +25,7 @@ defmodule RDF.Literal.Datatype.Registry do
"""
@spec datatype?(module) :: boolean
def datatype?(module) do
core_datatype?(module) or implements_datatype_behaviour?(module)
core_datatype?(module) or implements_behaviour?(module, Literal.Datatype)
end
@spec literal?(module) :: boolean
@ -43,10 +43,22 @@ defmodule RDF.Literal.Datatype.Registry do
def datatype(id) when maybe_ns_term(id), do: id |> Namespace.resolve_term!() |> datatype()
def datatype(id) when is_binary(id), do: Registration.datatype(id)
defp implements_datatype_behaviour?(module) do
@doc """
Returns the `RDF.XSD.Datatype` for a datatype IRI.
"""
@spec xsd_datatype(Literal.t | IRI.t | String.t) :: XSD.Datatype.t
def xsd_datatype(id) do
datatype = datatype(id)
if datatype && implements_behaviour?(datatype, XSD.Datatype) do
datatype
end
end
defp implements_behaviour?(module, behaviour) do
module.module_info[:attributes]
|> Keyword.get_values(:behaviour)
|> List.flatten()
|> Enum.member?(RDF.Literal.Datatype)
|> Enum.member?(behaviour)
end
end

View file

@ -76,6 +76,7 @@ defmodule RDF.XSD.Datatype do
"""
@callback init_invalid_lexical(any, Keyword.t()) :: String.t()
defdelegate get(id), to: RDF.Literal.Datatype.Registry, as: :xsd_datatype
defmacro __using__(opts) do
quote do

View file

@ -66,4 +66,22 @@ defmodule RDF.Literal.Datatype.RegistryTest do
assert Age == Datatype.Registry.datatype(EX.Age)
end
end
describe "xsd_datatype/1" do
test "when a core XSD datatype with the given IRI exists" do
assert XSD.String = Datatype.Registry.xsd_datatype(NS.XSD.string)
end
test "when a custom XSD datatype with the given IRI exists" do
assert Age = Datatype.Registry.xsd_datatype(EX.Age)
end
test "when datatype with the given IRI exists, but it is not an XSD datatype" do
refute Datatype.Registry.xsd_datatype(RDF.langString)
end
test "when no datatype with the given IRI exists" do
refute Datatype.Registry.xsd_datatype(EX.foo)
end
end
end