Skip to content

Commit

Permalink
GenServer post
Browse files Browse the repository at this point in the history
  • Loading branch information
toranb committed Oct 21, 2018
1 parent ab85792 commit 9596670
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 16 deletions.
19 changes: 4 additions & 15 deletions lib/example.ex
Original file line number Diff line number Diff line change
@@ -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
32 changes: 32 additions & 0 deletions lib/worker.ex
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 16 additions & 0 deletions test/worker_test.exs
Original file line number Diff line number Diff line change
@@ -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.