Created
March 10, 2016 02:12
-
-
Save todd/7572aaa523036f28f187 to your computer and use it in GitHub Desktop.
Learn Me Some Plug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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