In part 13 of my Elixir journey I'll share how to use aliases for modules.
Alias
If you have a long module name you can create an `alias` and use that to reference the original module.
defmodule Foo do
def add(num) do
num + 1
end
defmodule Bar do
def transform(list) do
add_one = &Foo.add/1
Enum.map(list, add_one)
end
end
defmodule Zap do
def speak(result) do
IO.puts "hello #{inspect result}"
end
end
end
defmodule Baz do
alias Foo.Bar, as: Bar
def fire(list) do
Bar.transform(list)
end
end
In this example the `Bar` alias allows us to avoid typing out the full module path `Foo.Bar`. The `as` parameter defaults to the last segment of the module name referenced so in this case it's redundant.
defmodule Baz do
alias Foo.Bar
def fire(list) do
Bar.transform(list)
end
end
Alias also offers the ability to define multiple aliases in a single line when both modules share a common parent.
defmodule Baz do
alias Foo.{Bar, Zap}
def fire(list) do
Bar.transform(list)
|> Zap.speak()
end
end