public
Last active

Demo of simple DSL

  • Download Gist
dsl.exs
Elixir
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#!/usr/bin/env elixir
defmodule DSL do
defmacro action(match, [do: body]) do
quote do
def handle_info(unquote(match) = arg, state) do
unquote(body)
{:ok, state}
end
end
end
defmacro createhandler(name, [do: body]) do
quote do
defmodule unquote(name) do
unquote(body)
end
end
end
def compile(namespace, file) do
content = File.read!(file)
content =
"""
defmodule #{namespace} do
#require #{inspect __MODULE__}
import #{inspect __MODULE__}
#{content}
end
"""
{_module, _} = Code.eval(content)
:ok
end
end
 
[file_name] = System.argv
DSL.compile "MyHandlers", file_name
 
# Below is how you test it from elixir
MyHandlers.TestHandler.handle_info({:x, 5}, {SomeState})
MyHandlers.TestHandler.handle_info({:y, 3, :erlang.now}, {SomeState})
output
1 2 3
./dsl.exs test.dsl
x: 5
random.uniform(3) -> 1
test.dsl
1 2 3 4 5 6 7 8 9 10 11 12
createhandler TestHandler do
action {:x, x} do
# printToScreen
IO.puts "x: #{inspect x}"
end
action {:y, y, seed} do
# example of calling erlang modules
:random.seed(seed)
value = :random.uniform(y)
IO.puts "random.uniform(#{y}) -> #{value} "
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.