Created
April 3, 2018 13:44
-
-
Save blackode/d69030ebc52f614148b8ae5003ab87dc to your computer and use it in GitHub Desktop.
Artilce Demonstration Project
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
defmodule Bank do | |
use GenServer | |
alias Bank.Cache | |
@moduledoc """ | |
Documentation for Bank. | |
""" | |
# client API | |
def start_link(cache_pid) do | |
GenServer.start_link(Bank, cache_pid, name: Bank) | |
end | |
def init cache_pid do | |
balance = Cache.get_balance(cache_pid) | |
{:ok, %{current_balance: balance, cache_pid: cache_pid}} | |
end | |
def get_current_balance() do | |
GenServer.call(Bank, :get) | |
end | |
def show_balance() do | |
IO.inspect(get_current_balance(), label: "Available Balance") | |
end | |
def deposit amount do | |
GenServer.cast(Bank, {:credit, amount}) | |
end | |
def with_draw amount do | |
transaction = GenServer.call(Bank, {:with_draw, amount}) | |
case transaction do | |
:ok -> | |
IO.inspect amount, label: "Amount debitted" | |
show_balance() | |
{:ok, error}-> | |
IO.inspect error.reason, label: "ERROR:" | |
end | |
end | |
# Server API | |
def handle_call(:get, _from, state) do | |
{:reply, state.current_balance, state} | |
end | |
def handle_call({:with_draw, with_draw_amount}, _from, %{current_balance: current_balance } = state) | |
when current_balance > with_draw_amount do | |
GenServer.cast(Bank, {:debit, with_draw_amount}) | |
{:reply, :ok, state} | |
end | |
def handle_cast({:credit,amount}, %{current_balance: current_balance}=state) do | |
new_balance = current_balance + amount | |
{:noreply, %{state | current_balance: new_balance } } | |
end | |
def handle_cast({:debit,amount}, %{current_balance: current_balance} = state) when amount < current_balance do | |
new_balance = current_balance - amount | |
{:noreply, %{state | current_balance: new_balance } } | |
end | |
def terminate(_reason, state) do | |
Cache.save_balance(state.current_balance, state.cache_pid) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment