Reputation: 1445
I have a macro which gets a module name as parameter and I want to call a function on that module to get some data in order to generate the quote
block.
Example:
defmacro my_macro(module) do
data = apply(module, :config, [])
# do something with data to generate the quote do end
end
Obviously, this doesn't work because the parameter value is quoted. I could fetch the data inside the quote block and act accordingly but that would put the whole logic inside the module that uses my macro which is quite dirty. I want to inject as little code as possible.
Upvotes: 0
Views: 335
Reputation: 222118
You can extract the module out by pattern matching with its quoted form: {:__aliases__, _, list}
where list
is a list of atoms which when concatenated with a dot (use Module.concat/1
) produces the full module name.
defmodule A do
defmacro my_macro({:__aliases__, _, list}) do
module = Module.concat(list)
module.foo()
end
end
defmodule B do
def foo do
quote do
42
end
end
end
defmodule C do
import A
IO.inspect my_macro B
end
Output:
42
Upvotes: 2