Created
May 29, 2015 02:51
-
-
Save MonkeyIsNull/670bed73ad704a43dbf9 to your computer and use it in GitHub Desktop.
OTP CatStore
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 Catstore.Server do | |
use GenServer | |
## really simple API | |
def new_store(cats) do | |
{:ok, store} = GenServer.start_link(Catstore.Server, cats) | |
store | |
end | |
def add(store, cat) do | |
GenServer.call(store, {:push_cat, cat}) | |
end | |
def remove(store, cat) do | |
GenServer.call(store, {:remove, cat}) | |
end | |
def list(store) do | |
GenServer.call(store, :list) | |
end | |
def close(store, reason) do | |
GenServer.cast(store, {:stop, reason}) | |
end | |
def pr_cats(cats) do | |
IO.puts "*** Your Cat Order ***" | |
Enum.each(cats, fn(cat) -> IO.puts(" Name: #{cat}") end) | |
IO.puts "**********************" | |
end | |
def init(cats) do | |
IO.puts "Starting with cats: #{cats}" | |
{:ok, cats} | |
end | |
def handle_call(:order, _pid, cats) do | |
{:reply, "Your order is being processed..", cats} | |
end | |
def handle_call(:list, _pid, cats) do | |
{:reply, pr_cats(cats), cats} | |
end | |
def handle_call({:push_cat, cat}, _pid, current_cats) do | |
IO.puts "Adding cat #{cat}" | |
{:reply, :ok, [ cat | current_cats ] } | |
end | |
def handle_call({:remove, cat}, _pid, current_cats) do | |
case cat in current_cats do | |
true -> | |
{:reply, {:ok, cat}, List.delete(current_cats, cat)} | |
false -> | |
{:reply, :not_found, current_cats} | |
end | |
end | |
def handle_cast({:stop, reason}, cats) do | |
IO.puts "Stopping because you said: #{reason}" | |
IO.puts "Ditching all cats #{cats}" | |
{:stop, reason, cats} | |
end | |
def terminate(_reason, _state) do | |
IO.puts "Terminated." | |
:ok | |
end | |
end | |
# To run | |
# {:ok, pid} = GenServer.start_link(Catstore.Server, ["Whiskers", "Tabby"]) | |
# To Add | |
# GenServer.call(pid, {:push_cat, "Miss Dainty"}) | |
# GenServer.call(pid, :list) | |
# To stop the madness | |
# GenServer.cast(pid, {:stop, "NO MOAR!"}) | |
# | |
# Our public API | |
# store = Catstore.Server.new_store(["Friskies", "Night"]) | |
# Catstore.Server.add(store, "Midnight") | |
# Catstore.Server.add(store, "Buckles") | |
# Catstore.Server.add(store, "Floppy") | |
# Catstore.Server.remove(store, "Midnight") | |
# Catstore.Server.list(store) | |
# Catstore.Server.close(store, "Closing time") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment