Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically access module by string or symbol?

Tags:

elixir

I'm trying to write a set of macros all of which would have to depend on the knowledge about the same module and hence, I'm trying to avoid passing this module explicitly to each function (I'm actually fine with doing so, but as I'm learning the language I'm trying to explore all the possibilities!).

So I'm writing (The goal is to access SomeOtherModule, or invoke 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 doesn't work as apply/3 expect a module and not a string or symbol representation of the module's name.

Basically, as the title says, I'm looking for some way to make it so that for a given string or symbol it would access the corresponding module or invoke a function of that module.

Also, I know that it's possible to access the current module via __MODULE__ in macro, but I'm looking for a way to access any existing module, not only the current one.

like image 436
user2205259 Avatar asked Sep 09 '15 04:09

user2205259


1 Answers

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

like image 130
bitwalker Avatar answered Nov 17 '22 20:11

bitwalker