feat: add toy registry

This commit is contained in:
Moritz Böhme 2024-08-09 12:19:57 +02:00
parent 7ba3b1cd4f
commit 53abb3b4aa
Signed by: moritz
GPG key ID: 970C6E89EB0547A9

37
other/simple_registry.ex Normal file
View file

@ -0,0 +1,37 @@
defmodule SimpleRegistry do
use GenServer
def start_link do
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end
def register(name) when is_atom(name) do
Process.link(Process.whereis(__MODULE__))
if :ets.insert_new(__MODULE__, {name, self()}) do
:ok
else
:error
end
end
def whereis(name) when is_atom(name) do
case :ets.lookup(__MODULE__, name) do
[{^name, value}] -> value
[] -> nil
end
end
@impl GenServer
def init(_) do
Process.flag(:trap_exit, true)
:ets.new(__MODULE__, [:named_table, :public])
{:ok, nil}
end
@impl GenServer
def handle_info({:EXIT, pid, _reason}, state) do
:ets.match_delete(__MODULE__, {:_, pid})
{:noreply, state}
end
end