Skip to content

Instantly share code, notes, and snippets.

@stolen
Created July 5, 2016 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stolen/0f83b3406b5c9eddc882a97d695ee0ec to your computer and use it in GitHub Desktop.
Save stolen/0f83b3406b5c9eddc882a97d695ee0ec to your computer and use it in GitHub Desktop.
Deserialized gen_server pattern
-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