fourletters_controller.ex 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. defmodule FourlettersWeb.FourlettersController do
  2. use FourlettersWeb, :controller
  3. import Fourletters.Troll
  4. import ABCD.Fourletters
  5. def fourletters(conn, %{"fourletters" => fourletters}) do
  6. if String.length(fourletters) == 4 do
  7. pid = case Supervisor.start_child(
  8. Fourletters.Troll,
  9. %{id: String.to_atom(fourletters), start: {ABCD.Fourletters, :start_link, [["oo"]]}}) do
  10. {:ok, pid} -> pid
  11. {:error, {:already_started, pid}} -> pid
  12. end
  13. messages = ABCD.Fourletters.get(pid)
  14. render(conn, "four.html", fourletters: fourletters, messages: messages)
  15. else
  16. redirect(conn, to: "/")
  17. end
  18. end
  19. def addletters(conn, _params) do
  20. %{params: params, path_params: path_params} = conn
  21. %{"fourletters" => fourletters, "message" => message} = params
  22. if String.length(fourletters) == 4 and String.length(message) < 101 do
  23. pid = case Supervisor.start_child(
  24. Fourletters.Troll,
  25. %{id: String.to_atom(fourletters), start: {ABCD.Fourletters, :start_link, [["oo"]]}}) do
  26. {:ok, pid} -> pid
  27. {:error, {:already_started, pid}} -> pid
  28. end
  29. messages = ABCD.Fourletters.put(pid, message)
  30. json(conn, %{fourletters: fourletters, messages: messages})
  31. else
  32. json(conn, %{error: message})
  33. end
  34. end
  35. def nothing(conn, _params) do
  36. render(conn, "nothing.html")
  37. end
  38. end