Sha256: 18e537d329673b75eae6081a0015231c3f04c28282620639884c440d10c165bf

Contents?: true

Size: 1.31 KB

Versions: 136

Compression:

Stored size: 1.31 KB

Contents

defmodule BankAccount do
  @moduledoc """
  A bank account that supports access from multiple processes.
  """

  use GenServer

  ## Callbacks

  def init(_args) do
    { :ok, 0 }
  end

  def handle_call(:balance, _from, balance) do
    { :reply, balance, balance }
  end

  def handle_call({ :update, amount }, _from, balance) do
    { :reply, :ok, balance + amount }
  end

  def handle_call(:close, _from, balance) do
    # We stop normally and return :stopped to the caller.
    { :stop, :normal, :stopped, balance }
  end

  ## Interface for tests

  @typedoc """
  An account handle.
  """
  @opaque account :: pid

  @doc """
  Open the bank. Makes the account available.
  """
  @spec open_bank() :: account
  def open_bank() do
    { :ok, pid } = :gen_server.start_link(BankAccount, [], [])
    pid
  end

  @doc """
  Close the bank. Makes the account unavailable.
  """
  @spec close_bank(account) :: any
  def close_bank(account) do
    :gen_server.call(account, :close)
  end

  @doc """
  Get the account's balance.
  """
  @spec balance(account) :: integer
  def balance(account) do
    :gen_server.call(account, :balance)
  end

  @doc """
  Update the account's balance by adding the given amount which may be negative.
  """
  def update(account, amount) do
    :gen_server.call(account, { :update, amount })
  end
end

Version data entries

136 entries across 136 versions & 1 rubygems

Version Path
trackler-2.0.8.39 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.38 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.37 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.36 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.35 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.34 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.33 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.32 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.31 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.30 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.29 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.28 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.27 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.26 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.24 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.23 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.22 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.21 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.20 tracks/elixir/exercises/bank-account/example.exs
trackler-2.0.8.19 tracks/elixir/exercises/bank-account/example.exs