Last active
December 12, 2015 07:59
-
-
Save khia/4741045 to your computer and use it in GitHub Desktop.
Demo of simple DSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
./dsl.exs test.dsl | |
x: 5 | |
random.uniform(3) -> 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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