Last active
August 29, 2015 14:14
-
-
Save os6sense/4d71a2e887e81050cc91 to your computer and use it in GitHub Desktop.
(sort of dynamic) alias as a macro in Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# dynamic_alias.ex | |
defmodule DynamicAlias do | |
@doc | |
""" | |
The following macro will introduce an alias into the calling module replacing | |
the last part of the module name with the contents of List.replace_at/3. | |
This is useful if you want to automatically references a different module | |
without knowing the fully qualified module name, but I'm new to Elixir and | |
there may be a better way to do this. | |
See tests for a complete example. | |
""" | |
defmacro __using__(_opts) do | |
quote do | |
alias unquote Module.split(__CALLER__.module) | |
|> List.replace_at(-1, "Baz") | |
|> Module.concat | |
end | |
end | |
end | |
# dynamic_alias_test | |
ExUnit.start | |
defmodule DynamicAlias.Baz do | |
def baz(), do: :baz | |
end | |
defmodule DynamicAlias.Test do | |
use ExUnit.Case | |
use DynamicAlias | |
test "DynamicAlias.Baz is aliased to Baz" do | |
assert DynamicAlias.Baz.baz() == :baz | |
assert Baz.baz() == :baz | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment