Skip to content

Instantly share code, notes, and snippets.

@cjbottaro
Created January 17, 2016 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjbottaro/6ee1ed0816892f09d126 to your computer and use it in GitHub Desktop.
Save cjbottaro/6ee1ed0816892f09d126 to your computer and use it in GitHub Desktop.
Dynamically define function using module attribute as name
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