-
-
Save cjbottaro/6ee1ed0816892f09d126 to your computer and use it in GitHub Desktop.
Dynamically define function using module attribute as name
This file contains hidden or 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
defmodule Definer do | |
defmacro define(do: block) do | |
quote bind_quoted: [block: Macro.escape(block)] do | |
func_name = @name |> String.to_atom |> Macro.var(__MODULE__) | |
def unquote(func_name) do | |
unquote(block) | |
end | |
end | |
end | |
end | |
defmodule Foo do | |
import Definer | |
@name "test_func" | |
define do | |
IO.puts "Hi, mom!" | |
end | |
end | |
Foo.test_func | |
# => Hi, mom! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment