Skip to content

Instantly share code, notes, and snippets.

@polvalente
Created July 11, 2019 22:45
Show Gist options
  • Save polvalente/93ca6baefc3f8f2e2abefbf5f200741a to your computer and use it in GitHub Desktop.
Save polvalente/93ca6baefc3f8f2e2abefbf5f200741a to your computer and use it in GitHub Desktop.
Create behaviour from a module
defmodule MakeBehaviour do
defmacro __using__(opts) do
module = opts[:module]
quote do
if not is_nil(unquote(module)) do
import unquote(module)
end
@on_definition {MakeBehaviour, :on_def}
end
end
def on_def(%{module: module}, :def, name, args, _guards, _body) do
Module.spec_to_callback(module, {name, length(args)})
end
def on_def(_, _, _, _, _, _), do: nil
end
defmodule ExampleModule do
use MakeBehaviour
@spec example() :: String.t()
def example, do: "this will become a callback"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment