Created
July 5, 2016 09:35
-
-
Save stolen/0f83b3406b5c9eddc882a97d695ee0ec to your computer and use it in GitHub Desktop.
Deserialized gen_server pattern
This file contains hidden or 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
-module(deser_gs). | |
-export([start_link/0]). | |
-export([init/1, handle_call/3, terminate/2]). | |
-export([hello/2, handle_hello/3]). | |
-export([world/1, handle_world/3]). | |
start_link() -> | |
gen_server:start_link(?MODULE, none, []). | |
init(none) -> | |
{ok, #{}}. | |
%% Generic call. API function provides a handler. | |
deser_call(Server, Function, Arg) -> | |
gen_server:call(Server, {'$deser_rpc', Function, Arg}). | |
handle_call({'$deser_rpc', Function, Arg}, From, State) -> | |
?MODULE:Function(Arg, From, State). | |
terminate(_, _) -> | |
ok. | |
hello(Server, Who) -> | |
deser_call(Server, handle_hello, Who). | |
handle_hello(Who, _From, #{} = State) -> | |
{reply, {hello, Who}, State#{hello => Who}}. | |
world(Server) -> | |
deser_call(Server, handle_world, none). | |
handle_world(none, _From, #{hello := Who} = State) -> | |
{reply, {Who, nearby}, State}; | |
handle_world(none, _From, #{} = State) -> | |
{reply, i_am_so_lonely, State}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment