Guest User

Untitled

a guest
Jan 18th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. defmodule Slug1 do
  2. def slugify(input), do: map_slug(input, %{pattern: ~r/\s+/})
  3.  
  4. def slugify2(input), do: map_slug(input, %{pattern: " "})
  5.  
  6. defp map_slug(input, %{pattern: pattern}) do
  7. input
  8. |> to_string()
  9. |> String.trim()
  10. |> String.downcase()
  11. |> String.replace(pattern, "-")
  12. end
  13. end
  14.  
  15. # ---
  16.  
  17. defmodule Slug2 do
  18. def slugify(input), do: map_slug(input, [pattern: ~r/\s+/])
  19.  
  20. def slugify2(input), do: map_slug(input, [pattern: " "])
  21.  
  22. defp map_slug(input, keywords) do
  23. pattern = Keyword.fetch!(keywords, :pattern)
  24.  
  25. input
  26. |> to_string()
  27. |> String.trim()
  28. |> String.downcase()
  29. |> String.replace(pattern, "-")
  30. end
  31. end
  32.  
  33. # ---
  34.  
  35. defmodule Slug3 do
  36. def slugify(input) do
  37. replacer(~r/\s+/)
  38. |> map_slug(input)
  39. end
  40.  
  41. def slugify2(input) do
  42. replacer(" ")
  43. |> map_slug(input)
  44. end
  45.  
  46. defp map_slug(replace, input) do
  47. to_string(input)
  48. |> String.trim()
  49. |> String.downcase()
  50. |> replace.()
  51. end
  52.  
  53. defp replacer(pattern) do
  54. &(String.replace(&1, pattern, "-"))
  55. end
  56. end
  57.  
  58. # ---
  59.  
  60. text = " I WILL be a url slug "
  61.  
  62. result_of = fn(fn_name, %{to: text}) ->
  63. &(apply(&1, fn_name, [text]))
  64. end
  65.  
  66. results_must_be_equal_to = fn(expected_text) ->
  67. &(&1 == expected_text)
  68. end
  69.  
  70. Enum.map([Slug1, Slug2, Slug3], result_of.(:slugify, %{to: text}))
  71. |> Enum.all?(results_must_be_equal_to.("i-will-be-a-url-slug"))
  72. |> IO.puts()
  73.  
  74. # ---
  75.  
  76. Enum.map([Slug1, Slug2, Slug3], &(apply(&1, :slugify2, [text])))
  77. |> Enum.all?(&(&1 == "i---will-be-a-url-slug"))
  78. |> IO.puts()
Add Comment
Please, Sign In to add comment