From 95966708c8522a8fb11a7b434db6767e6c6b211f Mon Sep 17 00:00:00 2001 From: toran billups Date: Sun, 21 Oct 2018 18:08:09 -0500 Subject: [PATCH] GenServer post --- lib/example.ex | 19 ++++--------------- lib/worker.ex | 32 ++++++++++++++++++++++++++++++++ mix.exs | 3 ++- test/worker_test.exs | 16 ++++++++++++++++ 4 files changed, 54 insertions(+), 16 deletions(-) create mode 100644 lib/worker.ex create mode 100644 test/worker_test.exs diff --git a/lib/example.ex b/lib/example.ex index ca49896..8488c20 100644 --- a/lib/example.ex +++ b/lib/example.ex @@ -1,18 +1,7 @@ -defmodule Example do - @moduledoc """ - Documentation for Example. - """ +defmodule EX.Application do + use Application - @doc """ - Hello world. - - ## Examples - - iex> Example.hello - :world - - """ - def hello do - :world + def start(_type, _args) do + EX.Worker.start_link(name: EX.Worker) end end diff --git a/lib/worker.ex b/lib/worker.ex new file mode 100644 index 0000000..dc5d3d8 --- /dev/null +++ b/lib/worker.ex @@ -0,0 +1,32 @@ +defmodule EX.Worker do + use GenServer + + def start_link(args) do + GenServer.start_link(__MODULE__, :ok, args) + end + + @impl GenServer + def init(:ok) do + state = Shortener.new() + {:ok, state} + end + + def get(pid, hash) do + GenServer.call(pid, {:get, hash}) + end + + def put(pid, hash, url) do + GenServer.cast(pid, {:put, hash, url}) + end + + @impl GenServer + def handle_call({:get, hash}, _timeout, state) do + {:reply, Shortener.get_url(state, hash), state} + end + + @impl GenServer + def handle_cast({:put, hash, url}, state) do + new_state = Shortener.create_short_url(state, hash, url) + {:noreply, new_state} + end +end diff --git a/mix.exs b/mix.exs index 06b6499..2a5ec11 100644 --- a/mix.exs +++ b/mix.exs @@ -14,7 +14,8 @@ defmodule Example.MixProject do # Run "mix help compile.app" to learn about applications. def application do [ - extra_applications: [:logger] + extra_applications: [:logger], + mod: {EX.Application, []} ] end diff --git a/test/worker_test.exs b/test/worker_test.exs new file mode 100644 index 0000000..5289b48 --- /dev/null +++ b/test/worker_test.exs @@ -0,0 +1,16 @@ +defmodule EX.WorkerTest do + use ExUnit.Case, async: true + + setup do + pid = start_supervised!(EX.Worker) + %{pid: pid} + end + + test "get and put work", %{pid: pid} do + assert EX.Worker.get(pid, "x") === :undefined + + EX.Worker.put(pid, "x", "google.com") + + assert EX.Worker.get(pid, "x") === "google.com" + end +end