Elixir — Dynamic Import
This won’t work in Elixir
alias Application.get_env(:app_name, :my_mod)
Solution
As you cannot import directly, you can do it through __using__ functionality provided.
So create a MyMod function and in __using__ function of this module alias it.
Why quote/unquote required
You can learn about quote/unquote here.
Brief Explanation
The building block of an Elixir program is a tuple with three elements. For example, the function call sum(1, 2, 3)
is represented internally as:
{:sum, [], [1, 2, 3]}
You can get the representation of any expression by using the quote
macro.
iex> quote do: sum(1, 2, 3)
{:sum, [], [1, 2, 3]}
But if you put variable in quote you will get result like
iex> number = 13
iex> quote do: sum(1, 2, number)
{:sum, [], [1, 2, {:number, [], Elixir}]}
To fix this you require unqoute
iex> number = 13
iex> quote do: sum(1, 2, unquote(number))
{:sum, [], [1, 2, 13]}