Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Last active May 7, 2016 16:43
Show Gist options
  • Select an option

  • Save StevenXL/90f48e7af3489792479cd62d8b677239 to your computer and use it in GitHub Desktop.

Select an option

Save StevenXL/90f48e7af3489792479cd62d8b677239 to your computer and use it in GitHub Desktop.
Elixir Supervisor Behavior
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