Last active
May 7, 2016 16:43
-
-
Save StevenXL/90f48e7af3489792479cd62d8b677239 to your computer and use it in GitHub Desktop.
Elixir Supervisor Behavior
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 GenServerSupervisor do | |
| use GenServer | |
| # Client API # | |
| def start_link(child_specs_list) do | |
| GenServer.start_link(__MODULE__, child_specs_list) | |
| end | |
| # Server API # | |
| def init(child_specs_list) do | |
| Process.flag(:trap_exit, true) | |
| state = child_specs_list |> start_children |> Enum.into(%{}) | |
| {:ok, state} | |
| end | |
| def handle_info({:EXIT, from, reason}, state) do | |
| case Map.get(state, from) do | |
| nil -> {:noreply, state} | |
| child_spec -> | |
| {:ok, pid} = start_child(child_spec) | |
| new_state = Map.delete(state, from) |> Map.put(pid, child_spec) | |
| {:noreply, new_state} | |
| end | |
| end | |
| # Helper Functions # | |
| defp start_children([child_spec | rest]) do | |
| case start_child(child_spec) do | |
| {:ok, pid} -> | |
| [{pid, child_spec} | start_children(rest)] | |
| :error -> :error | |
| end | |
| end | |
| defp start_children([]), do: [] | |
| defp start_child({module, fun, args}) do | |
| case apply(module, fun, args) do | |
| {:ok, pid} -> {:ok, pid} | |
| _ -> :error | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment