forked from rhruiz/my-own-genserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ex
50 lines (43 loc) · 1.1 KB
/
server.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule Server do
def call(pid, message) do
send(pid, {:call, self(), message})
receive do
{:reply, reply} -> reply
:noreply -> nil
m -> raise "unexpected message: #{inspect(m)}"
end
end
def cast(pid, message) do
send(pid, {:cast, message})
:ok
end
def start_link(module) do
spawn fn ->
handler(module, module.init(:ok))
end
end
def handler(module, state) do
receive do
{:call, from, message} ->
case module.handle_call(message, from, state) do
{:reply, reply, new_state} ->
send(from, {:reply, reply})
handler(module, new_state)
{:noreply, new_state} ->
send(from, :noreply)
handler(module, new_state)
m ->
send(from, {:unkown, m})
handler(module, state)
end
other ->
case module.handle_info(other, state) do
{:noreply, new_state} ->
handler(module, new_state)
m ->
raise "Invalid message #{inspect(m)}"
handler(module, state)
end
end
end
end