Current section
Files
Jump to
Current section
Files
lib/line-message/macro.ex
defmodule LineMessage.Macro do
defmacro __using__(_) do
quote do
import LineMessage.Macro
alias LineMessage.Event
alias LineMessage.Message
alias LineMessage.Reply
Reply.init
Event.start_link
Agent.start_link(fn -> Map.new end, name: EventAgent)
:ok
end
end
defmacro message(type \\ :any, [do: block]) do
quote do
event_on("message", unquote(type), fn -> unquote(block) end)
end
end
defmacro beacon(type \\ :any, [do: block]) do
quote do
event_on("beacon", unquote(type), fn -> unquote(block) end)
end
end
def event_on(event_type, message_type, func) do
LineMessage.Event.on(event_type, fn evt ->
evt_message_type = evt[String.to_atom(evt.type)].type
if evt_message_type == Atom.to_string(message_type)
or evt_message_type == "any" do
Agent.update(EventAgent, &Map.put(&1, self(), evt))
func.()
end
end)
end
def event do
{:ok, evt} = Agent.get(EventAgent, &Map.fetch(&1, self()))
evt
end
end