Dynamically Loading a Module in Elixir

Mustafa Turan
ElixirLabs
Published in
1 min readJul 29, 2016

Elixir way of keeping code clear and reusable is creating modules and importing them when needed. However import method is easy to use for static module names, it requires more afford to load dynamically assigned modules.

Suppose that you need to import, require a module using configuration. Then you can read the configuration by:

Application.get_env(:my_app, :module_ref)

And import, require like:

import Application.get_env(:my_app, :module_ref)
# or
require Application.get_env(:my_app, :module_ref)

But it wont work! An error will raise like:

invalid argument for import, expected a compile time atom or alias, got: Application.get_env(:my_app, :module_ref)

In order to ‘import’ or ‘require’ a module dynamically you need to create an ‘importer module’ like and import using macros:

defmodule MyApp.Importer do
@moduledoc """
Dynamically import configured module into your module.
### Examples
defmodule SomeModule do
...
use MyApp.Importer
...
def xyz do
...
some_func_from_ref_module()
...
end
end
"""
defmacro __using__(_) do
quote do
import unquote(Application.get_env(:my_app, :module_ref))
end
end

end
config :my_app,
module_ref: MyApp.SomeModule

When you need some dynamics in your code base, look into macros. Most probably solution will underly on quote and unquote tags.

--

--

Mustafa Turan
ElixirLabs

Go, Elixir, Ruby, Software Architecture, Microservices