Last active
August 29, 2015 14:07
-
-
Save mschae/77eed5c9e8c152efe3b3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 TrailingFormatCompatibilityPlug do | |
import Plug.Conn | |
def init(options), do: options | |
def call(conn, opts) do | |
conn.path_info |> List.last |> String.split(".") |> Enum.reverse |> case do | |
[ _ ] -> conn | |
[ format | fragments ] -> | |
new_path = fragments |> Enum.reverse |> Enum.join(".") | |
path_fragments = List.replace_at conn.path_info, -1, new_path | |
params = Plug.Conn.fetch_params(conn).params | |
|> Dict.put("format", format) | |
%{conn | path_info: path_fragments, params: params} | |
end | |
end | |
end |
This file contains hidden or 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 TrailingFormatCompatibilityPlugTest do | |
use ExUnit.Case, async: true | |
use Plug.Test | |
@opts TrailingFormatCompatibilityPlug.init([]) | |
test "plug removes trailing format" do | |
conn = conn(:get, "/foo/bar.json") | |
conn = TrailingFormatCompatibilityPlug.call(conn, @opts) | |
assert conn.path_info == ["foo", "bar"] | |
end | |
test "plug adds format to conn.params" do | |
conn = conn(:get, "/foo/bar.json") | |
|> Plug.Conn.fetch_params | |
conn = TrailingFormatCompatibilityPlug.call(conn, @opts) | |
assert conn.params["format"] == "json" | |
end | |
test "plug does nothing without trailing format" do | |
conn = conn(:get, "/foo/bar") | |
conn = TrailingFormatCompatibilityPlug.call(conn, @opts) | |
assert conn.path_info == ["foo", "bar"] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment