If I have some Struct on which I already defined all the required callbacks for a given Protocol, is there any way to just declare that without having to write a pile of defdelegate
stubs to tell defimpl
about my code?
@behaviour
does not seem to have this functionality, sadly… so is there something (else) in the standard library I’ve overlooked that would do, or render unnecessary, the following macro?
defmacro implements(protocol, callbacks, opts \\ []) do
module = __CALLER__.module
to = Keyword.get(opts, :delegate, module)
quote location: :keep do
defimpl unquote(protocol), for: unquote(module) do
unquote do
for {name, callback} <- callbacks do
case callback do
arity when is_integer(arity) ->
args = for _ <- (1..arity//1), do: Macro.unique_var(:"", __MODULE__)
quote do
defdelegate unquote(name)(unquote_splicing(args)), to: unquote(to)
end
fun when is_function(fun) ->
raise ArgumentError, "not implemented"
end
end
end
end
end
end