feat: add toy registry
This commit is contained in:
parent
7ba3b1cd4f
commit
53abb3b4aa
1 changed files with 37 additions and 0 deletions
37
other/simple_registry.ex
Normal file
37
other/simple_registry.ex
Normal 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
|
Loading…
Reference in a new issue