Hassle free Testing Elixir modules in iEx shell

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

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.

Did you find this article valuable?

Support AbulAsar S. by becoming a sponsor. Any amount is appreciated!