Skip to content

Instantly share code, notes, and snippets.

@alisinabh
Last active June 15, 2022 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alisinabh/24718a69b158bafa32938055e3d80061 to your computer and use it in GitHub Desktop.
Save alisinabh/24718a69b158bafa32938055e3d80061 to your computer and use it in GitHub Desktop.
Dynamically alias modules at compile time in Elixir with mox
defmodule DynamicAlias do
@moduledoc """
Helper macro to call the alias dynamically. This will allow developers to
stub the testing environment with a mock or use different modules with
different configuration without the need to use a runtime impl function.
Please note that this only works in compile time. Do not provide any runtime
specific configuration here.
"""
defmacro __using__(_env) do
mod = __MODULE__
quote do
require unquote(mod)
import unquote(mod)
end
end
@doc """
Aliases a function dynamically in a module.
## Parameters
- module: The dynamic function which will get you the module name.
(Don't use module attributes) as they are not available in here.
- options: All options accepted by `alias/2` like `:as`
## Examples
```elixir
defmodule MyModule do
use DynamicAlias
dynamic_alias :my_app, :calendar_impl, Calendar.ISO, as: Calendar
def utc_now do
DateTime.utc_now(Calendar)
end
end
```
"""
defmacro dynamic_alias(app, key_or_path, default, opts \\ []) do
module = Application.get_env(app, key_or_path, default)
quote do
alias unquote(module), unquote(opts)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment