I can dynamically define functions in a “loop” like this:
defmodule Foo do
for {f, i} <- [{:foo, "foo"}, {:bar, "bar"}] do
def foo(unquote(f)) do
unquote(i)
end
end
end
iex> Foo.foo(:foo)
"foo"
iex> Foo.foo(:bar)
"bar"
iex> Foo.foo(:baz)
💣
So that’s all cool
Now how do I do this inside of a macro? I’ve been at this for a few hours now and having a very hard time wrapping my head around it. The closest I’ve come is this:
defmodule Foo do
defmacro __using__(_) do
quote do
for {f, i} <- [{:foo, "foo"}, {:bar, "bar"}] do
defmacro foo(f) do
quote do
# unquote(i) <- This doesn't work so I'm commenting it out for now
end
end
end
end
end
end
This has the effect of defining def foo(:foo)
twice, even though I dbg(f)
in inside the inner macro and it has the correct values. On top of that, I can’t access i
inside the inner macro.
I got a bit of hint from this thread. I tried re-quoting that whole comprehension, capturing it in a variable, then quote(do: unquote_splicing(block))
it, but that didn’t work. There is more code that follows it so, I dunno.
I appreciate any help though if this serves as a rubber duck that’d be good too