From 24c4ba90800206a422f082a8c0517a8bffa86e6d Mon Sep 17 00:00:00 2001 From: Pedro Tavares Date: Tue, 9 Jul 2019 16:33:13 +0100 Subject: [PATCH] Make Horde.Supervisor child_spec overridable Fixes #107 --- lib/horde/supervisor.ex | 8 ++++++-- test/supervisor_test.exs | 20 ++++++++++++++++++++ test/support/module_based_supervisor.ex | 17 +++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/lib/horde/supervisor.ex b/lib/horde/supervisor.ex index 12cfa1ea..b43dbf0d 100644 --- a/lib/horde/supervisor.ex +++ b/lib/horde/supervisor.ex @@ -45,23 +45,27 @@ defmodule Horde.Supervisor do Then you can use `MySupervisor.child_spec/1` and `MySupervisor.start_link/1` in the same way as you'd use `Horde.Supervisor.child_spec/1` and `Horde.Supervisor.start_link/1`. """ - defmacro __using__(_opts) do + defmacro __using__(opts) do quote do @behaviour Horde.Supervisor def child_spec(options) do options = Keyword.put_new(options, :id, __MODULE__) - %{ + default = %{ id: Keyword.get(options, :id, __MODULE__), start: {__MODULE__, :start_link, [options]}, type: :supervisor } + + Supervisor.child_spec(default, unquote(Macro.escape(opts))) end def start_link(options) do Horde.Supervisor.start_link(Keyword.put(options, :init_module, __MODULE__)) end + + defoverridable child_spec: 1 end end diff --git a/test/supervisor_test.exs b/test/supervisor_test.exs index d9691175..0ee84db3 100644 --- a/test/supervisor_test.exs +++ b/test/supervisor_test.exs @@ -89,6 +89,26 @@ defmodule SupervisorTest do {:ok, members} = Horde.Cluster.members(:init_sup_test_1) assert 2 = Enum.count(members) end + + test "can use `child_spec` function to override defaults from Horde.Supervisor" do + assert %{ + id: 123, + start: + {TestSupervisor3, :start_link, + [ + custom_id: 123, + name: :init_sup_test_3, + strategy: :one_for_one + ]}, + restart: :transient, + type: :supervisor + } = + TestSupervisor3.child_spec( + custom_id: 123, + name: :init_sup_test_3, + strategy: :one_for_one + ) + end end describe ".start_child/2" do diff --git a/test/support/module_based_supervisor.ex b/test/support/module_based_supervisor.ex index 75f89378..46a70713 100644 --- a/test/support/module_based_supervisor.ex +++ b/test/support/module_based_supervisor.ex @@ -13,3 +13,20 @@ defmodule TestSupervisor2 do {:ok, Keyword.put(options, :members, [:init_sup_test_1, :init_sup_test_2])} end end + +defmodule TestSupervisor3 do + use Horde.Supervisor + + def init(options) do + {:ok, Keyword.put(options, :members, [:init_sup_test_3, :init_sup_test_3])} + end + + def child_spec(args) do + %{ + id: args[:id], + start: {__MODULE__, :start_link, [args]}, + restart: :transient, + type: :supervisor + } + end +end