From 273a75f4f9e3fdb8e5a437840cc34910355be33f Mon Sep 17 00:00:00 2001 From: Jamon Holmgren Date: Tue, 14 Mar 2017 12:33:58 -0700 Subject: [PATCH] Extracts normalize_url to utility function and adds doctests --- lib/thesis/controller.ex | 4 +--- lib/thesis/utilities.ex | 15 +++++++++++++++ test/utilities_test.exs | 4 ++++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 test/utilities_test.exs diff --git a/lib/thesis/controller.ex b/lib/thesis/controller.ex index 482865f..e5a83b0 100644 --- a/lib/thesis/controller.ex +++ b/lib/thesis/controller.ex @@ -90,9 +90,7 @@ defmodule Thesis.Controller.Plug do end def call(conn, _opts) do - url = conn.request_path - |> String.replace(~r/(?<=[^:])(\/\/)/, conn.request_path, "/") # Strip double slashes - |> String.replace(~r/\/$/, "") # Strip trailing slash + url = Thesis.Utilities.normalize_url(conn.request_path) current_page = store.page(url) page_contents = store.page_contents(current_page) diff --git a/lib/thesis/utilities.ex b/lib/thesis/utilities.ex index e66a6aa..3407bb2 100644 --- a/lib/thesis/utilities.ex +++ b/lib/thesis/utilities.ex @@ -3,6 +3,7 @@ defmodule Thesis.Utilities do Module that provides helper functions. """ + def parameterize(str) do str = Regex.replace(~r/[^a-z0-9\-\s\.]/i, str, "") Regex.split(~r/\%20|\s/, str) @@ -18,4 +19,18 @@ defmodule Thesis.Utilities do |> String.downcase |> binary_part(0, length) end + + @doc """ + Takes a URL and strips unnecessary characters. + + iex> Thesis.Utilities.normalize_url("http://infinite.red//ignite//foo") + "http://infinite.red/ignite/foo" + iex> Thesis.Utilities.normalize_url("https://infinite.red/ignite/foo/") + "https://infinite.red/ignite/foo" + """ + def normalize_url(url) do + url + |> String.replace(~r/(?<=[^:])(\/\/)/, "/") # Strip double slashes + |> String.replace(~r/\/$/, "") # Strip trailing slash + end end diff --git a/test/utilities_test.exs b/test/utilities_test.exs new file mode 100644 index 0000000..96fa785 --- /dev/null +++ b/test/utilities_test.exs @@ -0,0 +1,4 @@ +defmodule UtilitiesTest do + use ExUnit.Case + doctest Thesis.Utilities +end