Skip to content

Instantly share code, notes, and snippets.

@bongani-m
Created March 16, 2017 00:27
Show Gist options
  • Save bongani-m/bb66b8f3abd5271d61202fe931eba119 to your computer and use it in GitHub Desktop.
Save bongani-m/bb66b8f3abd5271d61202fe931eba119 to your computer and use it in GitHub Desktop.
Acccount Elixir Practice with GenServer impl
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