# Eratta Elixir In Action Chpt. 6 Listing 6.x pg. 170 | |
defmodule ServerProcess do | |
def start(callback_mod) do | |
spawn(fn -> | |
initial_state = callback_mod.init | |
loop(callback_mod, initial_state) | |
end) | |
end | |
def call(server_pid, request) do | |
send(server_pid, {:call, request, self }) | |
receive do | |
{:response, response} -> response | |
end | |
end | |
def cast(server_pid, request) do | |
send(server_pid, {:cast, request}) | |
end | |
defp loop(callback_mod, current_state) do | |
receive do | |
{:call, request, caller} -> | |
{response, new_state} = callback_mod.handle_call(request, current_state) | |
send(caller, {:response, response } ) | |
loop(callback_mod, new_state) | |
{:cast, request} -> | |
new_state = callback_mod.handle_cast( request, current_state ) | |
loop(callback_mod, new_state) | |
_ -> loop(callback_mod, current_state) | |
end | |
end | |
end | |
defmodule KeyValueStore do | |
@doc """ | |
To start this function run KeyValueStore.start | |
""" | |
def start do | |
ServerProcess.start(KeyValueStore) | |
end | |
def init do | |
HashDict.new | |
end | |
@doc """ | |
Example: KeyValueStore.put(pid, {:put, :key, :value}) | |
""" | |
def put(pid, key, value) do | |
ServerProcess.cast( pid, { :put, key, value } ) | |
end | |
def get(pid, key) do | |
ServerProcess.call( pid, { :get, key } ) | |
end | |
def handle_call({:put, key, value }, state) do | |
{:ok, HashDict.put( state, key, value) } | |
end | |
def handle_call( { :get, key }, state ) do | |
{ HashDict.get( state, key ), state } | |
end | |
def handle_cast({:put, key, value }, state) do | |
HashDict.put( state, key, value) | |
end | |
end | |
# > iex "server_process.ex" | |
# pid = ServerProcess.start(KeyValueStore) | |
# ServerProcess.call(pid, {:put, :key_one, :value_one}) | |
# ServerProcess.call(pid, {:get, :key_one}) | |
# kpid = KeyValueStore.start | |
# KeyValueStore.put(kpid, :some_key, :some_value) | |
# KeyValueStore.get(kpid, :some_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment