Permalink
Browse files

GenServer post

  • Loading branch information...
toranb committed Oct 21, 2018
1 parent ab85792 commit 95966708c8522a8fb11a7b434db6767e6c6b211f
Showing with 54 additions and 16 deletions.
  1. +4 −15 lib/example.ex
  2. +32 −0 lib/worker.ex
  3. +2 −1 mix.exs
  4. +16 −0 test/worker_test.exs
@@ -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
@@ -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
@@ -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

@@ -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

0 comments on commit 9596670

Please sign in to comment.