By what mechanism does iex load .beam files?

If I create a new directory and create a file called person.exs in that directory:

defmodule Person do
  def full_name(person) do
    "#{person.first_name} #{person.last_name}"
  end

  def age(person) do
    days = Date.diff(Date.utc_today(), person.birthday)
    days / 365.25
  end
end

And then I run iex and within IEx I run:

c "person.exs", "."

This creates a new file called Elixir.Person.beam. The Person module is then available within iex.

I can then quit that iex session and start a new one. Somehow Elixir.Person.Beam gets loaded here, and my Person module is available again without needing to “require” it.

What’s the mechanism behind this magic? Is it Elixir? Is it Erlang? From where does it come? Bonus points if your answer includes links to documentation from Elixir / Erlang explaining this.

Modules are loaded in iex dynamically (ie when a module is referenced but it is not known). Modules are loaded from the code path. As that doc says:

Initially, the code path consists of the current working directory and all Erlang object code directories under library directory $OTPROOT/lib, where $OTPROOT is the installation directory of Erlang/OTP, code:root_dir().

You can see your code path with :code.get_path/0.

6 Likes