Skip to content

Instantly share code, notes, and snippets.

@aseigo
Created August 13, 2018 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aseigo/3e6c1995f5e188b5b8bf3461bbc97824 to your computer and use it in GitHub Desktop.
Save aseigo/3e6c1995f5e188b5b8bf3461bbc97824 to your computer and use it in GitHub Desktop.
Conditional child specs idea sketch
--- a/lib/elixir/lib/supervisor.ex
+++ b/lib/elixir/lib/supervisor.ex
@@ -461,18 +461,25 @@ defmodule Supervisor do
@behaviour Supervisor
@opts unquote(opts)
+ @doc false
+ def should_start?(_arg), do: true
+
@doc false
def child_spec(arg) do
- default = %{
- id: __MODULE__,
- start: {__MODULE__, :start_link, [arg]},
- type: :supervisor
- }
+ if should_start?(arg) do
+ default = %{
+ id: __MODULE__,
+ start: {__MODULE__, :start_link, [arg]},
+ type: :supervisor
+ }
- Supervisor.child_spec(default, @opts)
+ Supervisor.child_spec(default, @opts)
+ else
+ nil
+ end
end
- defoverridable child_spec: 1
+ defoverridable child_spec: 1, should_start?: 0
@doc false
def init(arg)
@@ -615,7 +622,14 @@ defmodule Supervisor do
intensity = Keyword.get(options, :max_restarts, 3)
period = Keyword.get(options, :max_seconds, 5)
flags = %{strategy: strategy, intensity: intensity, period: period}
- {:ok, {flags, Enum.map(children, &init_child/1)}}
+ {:ok, {flags, Enum.reduce(children, [], &maybe_init_child/2) |> Enum.reverse()}}
+ end
+
+ defp maybe_init_child(child, acc) do
+ case init_child(child) do
+ nil -> acc
+ spec -> [spec | acc]
+ end
end
defp init_child(module) when is_atom(module) do
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment