Skip to content

Instantly share code, notes, and snippets.

@rranelli
Last active March 14, 2017 14:34
Show Gist options
  • Save rranelli/698135cab68577e7fa44e768ea79bc5a to your computer and use it in GitHub Desktop.
Save rranelli/698135cab68577e7fa44e768ea79bc5a to your computer and use it in GitHub Desktop.
defmodule SimpleBus do
def init do
{:ok, _} = Registry.start_link(:duplicate, __MODULE__)
end
def register_handler(module) do
Registry.register(__MODULE__, :event, module)
end
def emit(event_name, args) do
{:ok, agent} = Agent.start_link(fn -> nil end)
Registry.dispatch __MODULE__, :event, fn entries ->
result = for {_pid, module} <- entries do
{module, module.handle_event(event_name, args)}
end
Agent.update(agent, fn _ -> result end)
end
results = Agent.get(agent, & &1)
Agent.stop(agent)
for {handler, result} <- results, result != :ignored do
{handler, result}
end
end
end
defmodule Handler do
defmacro __using__(_) do
quote do
@before_compile Handler
end
end
defmacro __before_compile__(_) do
quote do
def handle_event(_, _), do: :ignored
end
end
end
defmodule Handler1 do
use Handler
def handle_event(:tuff, lek), do: IO.inspect lek
end
SimpleBus.init
SimpleBus.emit(:tuff, "leklek")
SimpleBus.emit(:LOL, nil)
SimpleBus.register_handler(Handler1)
SimpleBus.emit(:tuff, "leklek")
SimpleBus.emit(:LOL, nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment