Skip to content

Instantly share code, notes, and snippets.

@vothane
Created October 11, 2015 20:55
Show Gist options
  • Save vothane/e88017c239b76eda8bcf to your computer and use it in GitHub Desktop.
Save vothane/e88017c239b76eda8bcf to your computer and use it in GitHub Desktop.
replacing command pattern with functions in Elixir
defmodule CashRegister do
def new do
Agent.start_link(fn -> 0 end)
end
def add(pid, amount) do
Agent.update(pid, fn(register) -> register + amount end)
end
def reset(pid) do
Agent.update(pid, fn(register) -> 0 end)
end
def get(pid) do
Agent.get(pid, fn(register) -> register end)
end
end
ExUnit.start
defmodule CashRegisterTest do
use ExUnit.Case
test "cashier" do
{:ok, pid} = CashRegister.new
assert CashRegister.get(pid) == 0
CashRegister.add(pid, 100)
assert CashRegister.get(pid)== 100
CashRegister.add(pid, 20)
assert CashRegister.get(pid)== 120
CashRegister.reset(pid)
assert CashRegister.get(pid)== 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment