Created
July 23, 2018 17:31
-
-
Save termoose/913d311152d5b7a4bcb3c7d62571add5 to your computer and use it in GitHub Desktop.
Elixir callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Mod do | |
use GenServer | |
def start_link(_args) do | |
GenServer.start_link(__MODULE__, :ok) | |
end | |
def init(:ok) do | |
send(self(), :work) | |
{:ok, :ok} | |
end | |
@callback handle_work() :: any | |
defmacro __using__(opts) do | |
quote location: :keep do | |
use GenServer # Just to get the child_spec | |
@behaviour Mod | |
# Inject a default implementation on `use` | |
def handle_work() do | |
IO.puts "Not implemented!" | |
end | |
defoverridable [handle_work: 0] | |
end | |
end | |
def handle_info(:work, state) do | |
IO.puts "Work!" | |
handle_work() # Calling the defined callback hopefully | |
Process.send_after(self(), :work, 1_000) | |
{:noreply, state} | |
end | |
end | |
defmodule Using do | |
use Mod | |
def start_link(args) do | |
Mod.start_link(args) | |
end | |
def handle_work() do | |
IO.puts "Implemented!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment