Skip to content

Instantly share code, notes, and snippets.

@chrismccord
Last active March 29, 2017 03:35
Show Gist options
  • Save chrismccord/e0eaefe30d2ecd85b4ac to your computer and use it in GitHub Desktop.
Save chrismccord/e0eaefe30d2ecd85b4ac to your computer and use it in GitHub Desktop.
# in your app supervisor
:phx_dyn_dispatch = :ets.new(:phx_dyn_dispatch, [:named_table, :bag, :public])
defmodule DynamicDispatch do
def register(group, plug, opts) do
true = :ets.insert(:phx_dyn_dispatch, {group, plug, opts})
end
def unregister(group, plug) do
true = :ets.match_delete(:phx_dyn_dispatch, {group, plug, :_})
end
def init(opts), do: opts
def call(conn, group: group) do
Enum.reduce_while(:ets.lookup(:phx_dyn_dispatch, group), conn, fn
{_, _plug, _opts}, %Plug.Conn{halted: true} = acc -> {:halt, acc}
{_, plug, opts}, %Plug.Conn{} = acc -> {:cont, plug.call(acc, opts)}
end)
end
end
# in your existing router
forward "/", DynamicDispatch, []
# register your router/plug at any time
DynamicDispatch.register(:app, MyOtherRouter, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment