Skip to content

Instantly share code, notes, and snippets.

@scottmascio2115
Last active December 18, 2016 20:14
Show Gist options
  • Save scottmascio2115/74b6f67d299a44b61b34941ee26fdaeb to your computer and use it in GitHub Desktop.
Save scottmascio2115/74b6f67d299a44b61b34941ee26fdaeb to your computer and use it in GitHub Desktop.

Revisions

  1. scottmascio2115 revised this gist Dec 10, 2016. 1 changed file with 22 additions and 7 deletions.
    29 changes: 22 additions & 7 deletions todo.exs
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,26 @@
    defmodule Todo do
    use GenServer

    def init(tasks // "") do
    {:ok, tasks}
    ## Client side code
    def start(tasks \\ "") do
    {:ok, pid} = GenServer.start(__MODULE__, tasks)
    pid
    end

    def add_task(pid, task) do
    GenServer.cast(pid, {:add, task})
    end

    def remove_task(pid, task) do
    GenServer.cast(pid, {:remove, task})
    end

    def all_tasks(pid) do
    GenServer.call(pid, :all)
    end

    ## Server side code:

    def handle_cast({:add, task}, tasks) do
    {:noreply, tasks <> " | " <> task}
    end
    @@ -18,10 +34,9 @@ defmodule Todo do
    end
    end

    # {:ok, pid} = GenServer.start(Todo, "foo")
    # tasks = GenServer.call(pid, :all)
    # GenServer.cast(pid, {:add, "bar"})
    # GenServer.cast(pid, {:remove, "bar"})
    # pid = Todo.start
    # Todo.add_task(pid, "Make eggs")
    # Todo.all_tasks(pid)

    ## TODO
    # Encapsolate the GenServer logic in the module
    # Ask user for what it wants to do.
  2. scottmascio2115 created this gist Dec 9, 2016.
    27 changes: 27 additions & 0 deletions todo.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    defmodule Todo do
    use GenServer

    def init(tasks // "") do
    {:ok, tasks}
    end

    def handle_cast({:add, task}, tasks) do
    {:noreply, tasks <> " | " <> task}
    end

    def handle_cast({:remove, task}, tasks) do
    {:noreply, tasks |> String.replace("| #{task}", "")}
    end

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

    # {:ok, pid} = GenServer.start(Todo, "foo")
    # tasks = GenServer.call(pid, :all)
    # GenServer.cast(pid, {:add, "bar"})
    # GenServer.cast(pid, {:remove, "bar"})

    ## TODO
    # Encapsolate the GenServer logic in the module