Created
March 16, 2017 00:27
-
-
Save bongani-m/bb66b8f3abd5271d61202fe931eba119 to your computer and use it in GitHub Desktop.
Acccount Elixir Practice with GenServer impl
This file contains 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 Account do | |
use GenServer | |
# Helper Methods | |
def new do | |
{_, acc} = start_link() | |
acc | |
end | |
def deposit(account, amount) do | |
GenServer.cast(account, {:deposit, amount}) | |
end | |
def withdraw(account, amount) do | |
GenServer.cast(account, {:withdraw, amount}) | |
end | |
def balance(account) do | |
GenServer.call(account, {:balance}) | |
end | |
# callbacks | |
def start_link do | |
GenServer.start_link(__MODULE__, :ok, []) | |
end | |
def init(:ok) do | |
{:ok, 0} | |
end | |
def handle_cast({:withdraw, amount}, state) do | |
new_state = state - amount | |
{:noreply, new_state} | |
end | |
def handle_cast({:deposit, amount}, state) do | |
new_state = state + amount | |
{:noreply, new_state} | |
end | |
def handle_call({:balance}, _from, state) do | |
{:reply, state, state} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment