I'm currently learning/reading metaprogramming elixir
I managed to generate a function that puts it's name using macros:
defmodule MyMacros do
defmacro fun_gen(name) do
atom_name = elem(name, 0)
str_name = atom_name |> to_string
quote do
def unquote(name) do
IO.puts unquote(str_name)
end
end
end
end
defmodule My do
require MyMacros
MyMacros.fun_gen(bar)
end
the result:
iex(1)> My.bar
bar
:ok
so this is great :) but I was wondering if it was possible to generate several functions using a Enum.each or something like that:
defmodule MyMacros do
defmacro fun_gen(name) do
atom_name = elem(name, 0)
str_name = atom_name |> to_string
quote do
def unquote(name) do
IO.puts unquote(str_name)
end
end
end
end
defmodule My do
require MyMacros
loop (~w(foo bar baz) do
MyMacros.fun_gen(item)
end
end
Is there a way of looping in order to generate source code ? Thank you !