Skip to content

Instantly share code, notes, and snippets.

@todd
Created March 10, 2016 02:12
Show Gist options
  • Save todd/7572aaa523036f28f187 to your computer and use it in GitHub Desktop.
Save todd/7572aaa523036f28f187 to your computer and use it in GitHub Desktop.
Learn Me Some Plug
defmodule LearningPlug do
use Plug.Builder
plug Plug.Logger
plug :extract_name
plug :greet, %{my_option: "Hello"}
def extract_name(%Plug.Conn{request_path: "/" <> name} = conn, opts) do
assign(conn, :name, the_name(name))
end
def greet(conn, opts) do
conn
|> send_resp(200, "#{opts[:my_option]}, #{conn.assigns.name}")
end
defp the_name(name) do
if (String.length(name) == 0), do: "foobar", else: name
end
end
defmodule LearningPlugTest do
use ExUnit.Case
use Plug.Test
doctest LearningPlug
test "responds with 'Hello, foobar' for no name provided" do
conn = conn(:get, "/", "")
|> LearningPlug.call(%{})
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "Hello, foobar"
end
test "responds with 'Hello, todd' for name todd provided" do
conn = conn(:get, "/todd", "")
|> LearningPlug.call(%{})
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "Hello, todd"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment