Hassle free Testing Elixir modules in iEx shell

While working on Elixir project, we often test our functions or modules code in iex shell. Whatever change we make in our code, we fire iex -S mix command and all of our project modules are accessible in shell. Suppose, we have a module say Calculator which is nested under project mathematics directory . As per Elixir naming convention we are going to name that module as Mathematics.Calculator. We also implemented some function say square in this module.

defmodule Mathematics.Calculator do
  def square(number) do
    number*number
  end
end

For testing this square function we fire up iex shell. In Elixir, we have concept of alias using it we can avoid writing long module name. Using alias we can avoid Mathematics.Calculator, instead we can only use last word i.e Calculator. Refer example below.

> alias Mathematics.Calculator
> Calculator.square(2)
#=> 4

This looks fine but what if we add some more modules with deep level nesting modules say Mathematics.Logirithmic.LogCalculator. It becomes very cumbersome to alias these long named modules every-time we fire iex shell.

Solution :

Create a file .iex.exs at root level of your Elixir project directory. Add all the frequently used or long named alias in the file.

alias Mathematics.Calculator
alias Mathematics.Logrithmic.LogCalculator

Next time when you fire up iex, you don't have to alias these modules again. It will be directly accessible in the shell.

Hope, you like this easy little hack. Let me know your thoughts.

Iaam Onkara's photo

so in your example above both types of Calculator will be aliased as Calculator hence the only Calculator you will have access to thru Alias will be Logrithmic one.

Better to do

alias Mathematics.Calculator
alias Mathematics.Logrithmic.Calculator, as: LogCalc
AbulAsar Sayyad's photo

Ah, thanks for pointing. I randomly added that example. I'll change it. Thanks

Muhammad Ibrahim Shaikh's photo

Wow! This a very well written article on how to use alias. Would you mind if I copy it or embed it in my blog?

Mohd Shad Mirza's photo

Very well written AbulAsar Sayyad