template for gen_server


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. -module(module).
  2. -compile(export_all).
  3.  
  4. -behaviour(gen_server).
  5. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
  6.  
  7. %% Public API
  8.  
  9. start() ->
  10. gen_server:start({local, ?MODULE}, ?MODULE, [], []).
  11.  
  12. stop() ->
  13. gen_server:call(?MODULE, stop).
  14.  
  15. state() ->
  16. gen_server:call(?MODULE, state).
  17.  
  18. %% Server implementation, a.k.a.: callbacks
  19.  
  20. init([]) ->
  21. say("init", []),
  22. {ok, []}.
  23.  
  24. handle_call(stop, _From, State) ->
  25. say("stopping by ~p, state was ~p.", [_From, State]),
  26. {stop, normal, stopped, State};
  27.  
  28. handle_call(state, _From, State) ->
  29. say("~p is asking for the state.", [_From]),
  30. {reply, State, State};
  31.  
  32. handle_call(_Request, _From, State) ->
  33. say("call ~p, ~p, ~p.", [_Request, _From, State]),
  34. {reply, ok, State}.
  35.  
  36. handle_cast(_Msg, State) ->
  37. say("cast ~p, ~p.", [_Msg, State]),
  38. {noreply, State}.
  39.  
  40. handle_info(_Info, State) ->
  41. say("info ~p, ~p.", [_Info, State]),
  42. {noreply, State}.
  43.  
  44. terminate(_Reason, _State) ->
  45. say("terminate ~p, ~p", [_Reason, _State]),
  46. ok.
  47.  
  48. code_change(_OldVsn, State, _Extra) ->
  49. say("code_change ~p, ~p, ~p", [_OldVsn, State, _Extra]),
  50. {ok, State}.
  51.  
  52. %% Some helper methods.
  53.  
  54. say(Format) ->
  55. say(Format, []).
  56. say(Format, Data) ->
  57. io:format("~p:~p: ~s~n", [?MODULE, self(), io_lib:format(Format, Data)]).

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.