Skip to content

Instantly share code, notes, and snippets.

@khia
Last active December 12, 2015 07:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khia/4741045 to your computer and use it in GitHub Desktop.
Save khia/4741045 to your computer and use it in GitHub Desktop.
Demo of simple DSL
#!/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})
./dsl.exs test.dsl
x: 5
random.uniform(3) -> 1
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment