Skip to content

Commit

Permalink
Withdraw funds
Browse files Browse the repository at this point in the history
  • Loading branch information
grahamrhay committed Apr 7, 2018
1 parent a473057 commit 03ee427
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/bank_statem.erl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

-behaviour(gen_statem).

-export([start/0, stop/0, get_balance/0, close/0, reopen/0, deposit/1]).
-export([start/0, stop/0, get_balance/0, close/0, reopen/0, deposit/1, withdraw/1]).
-export([init/1, callback_mode/0]).
-export([open/3, closed/3]).

Expand All @@ -23,6 +23,9 @@ reopen() ->
deposit(Amount) ->
gen_statem:call(name(), {deposit, Amount}).

withdraw(Amount) ->
gen_statem:call(name(), {withdraw, Amount}).

stop() ->
gen_statem:stop(name()).

Expand All @@ -39,7 +42,11 @@ open({call, From}, close, Data) ->

open({call, From}, {deposit, Amount}, #{balance:=Balance} = Data) when is_number(Amount) andalso Amount > 0 ->
NewBalance = Balance + Amount,
{keep_state, Data#{balance:=NewBalance}, [{reply, From, deposit_made}]}.
{keep_state, Data#{balance:=NewBalance}, [{reply, From, deposit_made}]};

open({call, From}, {withdraw, Amount}, #{balance:=Balance} = Data) when is_number(Amount) ->
NewBalance = Balance - Amount,
{keep_state, Data#{balance:=NewBalance}, [{reply, From, withdrawal_made}]}.

closed({call, From}, reopen, Data) ->
{next_state, open, Data, [{reply, From, open}]}.
4 changes: 4 additions & 0 deletions test/bank_statem_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ deposit_test() ->
negative_deposit_test() ->
From = self(),
?assertError(function_clause, bank_statem:open({call, From}, {deposit, -1}, #{balance=>100})).

withdraw_test() ->
From = self(),
{keep_state, #{balance:=100}, [{reply, From, withdrawal_made}]} = bank_statem:open({call, From}, {withdraw, 100}, #{balance=>200}).

0 comments on commit 03ee427

Please sign in to comment.