Skip to content

Commit

Permalink
Add child_spec to using macro
Browse files Browse the repository at this point in the history
  • Loading branch information
Azolo committed Jan 22, 2018
1 parent a17b6fb commit 3bdc9c8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
24 changes: 23 additions & 1 deletion lib/websockex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,32 @@ defmodule WebSockex do

@optional_callbacks format_status: 2

defmacro __using__(_) do
defmacro __using__(opts) do
quote location: :keep do
@behaviour WebSockex

if Kernel.function_exported?(Supervisor, :child_spec, 2) do
@doc false
def child_spec(conn_info, state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [conn_info, state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end

@doc false
def child_spec(state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end

defoverridable child_spec: 2, child_spec: 1
end

@doc false
def handle_connect(_conn, state) do
{:ok, state}
Expand Down
31 changes: 31 additions & 0 deletions test/websockex_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1405,4 +1405,35 @@ defmodule WebSockexTest do
# A second data tuple means pretty output for `:observer`. Who knew?
assert {:data, _data} = List.keyfind(rest, :data, 0)
end

if Kernel.function_exported?(Supervisor, :child_spec, 2) do
describe "child_spec" do
test "child_spec/2" do
assert %{id: TestClient, start: {TestClient, :start_link, ["url", :state]}} =
TestClient.child_spec("url", :state)
end

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

test "child_spec is overridable" do
defmodule ChildSpecTest do
use WebSockex

def child_spec(_state) do
"hippo"
end

def child_spec(_conn, _state) do
"llama"
end
end

assert ChildSpecTest.child_spec(1, 2) == "llama"
assert ChildSpecTest.child_spec(1) == "hippo"
end
end
end

0 comments on commit 3bdc9c8

Please sign in to comment.