Guest User

Untitled

a guest
Jul 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. defmodule Mock.Server do
  2. use GenServer
  3.  
  4. # API
  5.  
  6. def start_link(responses) do
  7. GenServer.start_link(__MODULE__, responses)
  8. end
  9.  
  10. def request(pid, type) do
  11. GenServer.call(pid, {:request, type})
  12. end
  13.  
  14. def get_last_response(pid) do
  15. GenServer.call(pid, :get_last_response)
  16. end
  17.  
  18. # CALLBACKS
  19. def init(responses) do
  20. {:ok, %{last_response: :not_called, responses: responses}}
  21. end
  22.  
  23. def handle_call({:request, type}, _from, state) do
  24. case state[:responses][type] do
  25. [] ->
  26. {:stop, :cannot_handle_more_requests, state}
  27.  
  28. [response | responses] ->
  29. new_state =
  30. state
  31. |> put_in([:last_response], response)
  32. |> put_in([:responses, type], responses)
  33.  
  34. {:reply, response, new_state}
  35. end
  36. end
  37.  
  38. def handle_call(:get_last_response, _from, state) do
  39. {:reply, state[:last_response], state}
  40. end
  41. end
Add Comment
Please, Sign In to add comment