Skip to content

Commit

Permalink
Support child_spec/1 for Elixir 1.6 supervisors
Browse files Browse the repository at this point in the history
  • Loading branch information
ericentin committed May 12, 2018
1 parent d3a1c55 commit 089ac55
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/gen_state_machine.ex
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ defmodule GenStateMachine do

@doc false
defmacro __using__(args) do
callback_mode = Keyword.get(args, :callback_mode, :handle_event_function)
{callback_mode, args} = Keyword.pop(args, :callback_mode, :handle_event_function)

quote location: :keep do
@behaviour GenStateMachine
Expand Down Expand Up @@ -520,7 +520,20 @@ defmodule GenStateMachine do
:undefined
end

overridable_funcs = [init: 1, terminate: 3, code_change: 4]
@doc false
def child_spec(arg) do
default = %{id: __MODULE__, start: {__MODULE__, :start_link, [arg]}}

Enum.reduce(unquote(args), default, fn
{key, value}, acc when key in [:id, :start, :restart, :shutdown, :type, :modules] ->
Map.put(acc, key, value)

{key, _value}, _acc ->
raise ArgumentError, "unknown key #{inspect(key)} in child specification override"
end)
end

overridable_funcs = [init: 1, terminate: 3, code_change: 4, child_spec: 1]

overridable_funcs =
if @gen_statem_callback_mode == :handle_event_function do
Expand Down
22 changes: 22 additions & 0 deletions test/gen_state_machine_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,28 @@ defmodule GenStateMachineTest do
]
end

defmodule CustomChildSpec do
use GenStateMachine,
id: :id,
restart: :temporary,
shutdown: :infinity,
start: {:foo, :bar, []}
end

test "child_spec/1" do
assert EventFunctionSwitch.child_spec([:hello]) == %{
id: EventFunctionSwitch,
start: {EventFunctionSwitch, :start_link, [[:hello]]}
}

assert CustomChildSpec.child_spec([:hello]) == %{
id: :id,
restart: :temporary,
shutdown: :infinity,
start: {:foo, :bar, []}
}
end

@gen_statem_callback_mode_callback Application.loaded_applications()
|> Enum.find_value(fn {app, _, vsn} ->
app == :stdlib and vsn
Expand Down

0 comments on commit 089ac55

Please sign in to comment.