Last active
August 29, 2015 13:57
-
-
Save tylerflint/9666984 to your computer and use it in GitHub Desktop.
playing around with elixir macros
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 __using__(_opts) do | |
quote do | |
import Dsl | |
@before_compile Dsl | |
@list Keyword.new | |
end | |
end | |
defmacro set(key, val) do | |
quote do | |
@list Keyword.put(@list, unquote(key), unquote(val)) | |
end | |
end | |
defmacro __before_compile__(_) do | |
quote do | |
def get(key) do | |
Keyword.get @list, key | |
end | |
end | |
end | |
end | |
defmodule Foozle do | |
use Dsl | |
set :foo, "bar" | |
set :baz, "boa" | |
def test do | |
IO.puts "foo: #{get(:foo)}" | |
IO.puts "baz: #{get(:baz)}" | |
end | |
end | |
IO.puts Foozle.test | |
# output: | |
# foo: bar | |
# baz: boa |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment