Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 52 lines (39 sloc) 1.376 kB
7d8d868 @jixiuf new file: kitty.erl
authored
1 -module(kitty).
2 -compile([export_all]).
3 -behaviour(gen_server).
4 -record(cat, {name, color=green, description}).
5
6 start_link() -> gen_server:start_link(?MODULE, [], []).
7 %% Synchronous call
8 order_cat(Pid, Name, Color, Description) ->
9 gen_server:call(Pid, {order, Name, Color, Description}).
10
11 %% This call is asynchronous
12 return_cat(Pid, Cat = #cat{}) ->
13 gen_server:cast(Pid, {return, Cat}).
14
15 %% Synchronous call
16 close_shop(Pid) ->
17 gen_server:call(Pid, terminate).
18
19 init([]) ->
20
21 {ok, []}. %% no treatment of info here!
22
23 handle_call({order, Name, Color, Description}, _From, Cats) ->
24
25 if Cats =:= [] ->
26 {reply, make_cat(Name, Color, Description), Cats};
27 Cats =/= [] ->
28 {reply, hd(Cats), tl(Cats)}
29 end;
30 handle_call(terminate, _From, Cats) ->
31 {stop, normal, ok, Cats}.
32
33 handle_cast({return, Cat = #cat{}}, Cats) ->
34 {noreply, [Cat|Cats]}.
35
36 handle_info(Msg, Cats) ->
37 io:format("Unexpected message: ~p~n",[Msg]),
38 {noreply, Cats}.
39
40 terminate(normal, Cats) ->
41 [io:format("~p was set free.~n",[C#cat.name]) || C <- Cats],
42 ok.
43
44 code_change(_OldVsn, State, _Extra) ->
45 %% No change planned. The function is there for the behaviour,
46 %% but will not be used. Only a version on the next
47 {ok, State}.
48
49 %%% Private functions
50 make_cat(Name, Col, Desc) ->
51 #cat{name=Name, color=Col, description=Desc}.
Something went wrong with that request. Please try again.