Is it possible to dynamically access a module by string or character?

I am trying to write a set of macros, all of which would have to depend on knowledge of the same module, and therefore, I try not to pass this module explicitly to each function (I’m really fine since I’m learning the language, I’m trying to learn everything capabilities!).

So I'm writing (The goal is to access SomeOtherModule or call SomeOtherModule.foo inside the generated foo function.)

 defmodule MacrosUser do use MyMacros, SomeOtherModule end defmodule MyMacros do defmacro __using__(opts) do {:__aliases__, _, module_path} = opts quote do def foo do module_path |> Enum.join(".") |> apply(:foo, []) end end end end 

But this obviously does not work, since apply/3 expects a module, not a string or symbolic representation of the module name.

Basically, as the name says, I’m looking for a way to make it so that for a given line or character, it will access the corresponding module or call the function of this module.

In addition, I know that you can access the current module through __MODULE__ in the macro, but I'm looking for a way to access any existing module, not just the current one.

+6
source share
1 answer

Use Module.concat(module_path) instead of manually joining the path as it is for this purpose.

+11
source

All Articles