Jonas Dellinger
Jonas Dellinger

Reputation: 1364

Import functions of a dynamically loaded module

I have the following two files:

# script.exs
Code.eval_file("module.ex");

import MyModule # Doesn't work
my_function() # What I want
# module.ex

defmodule MyModule do
  def my_function() do
    IO.puts "My Function"
  end
end

When running elixir script.exs, it errors with the following message:

** (CompileError) script.exs:3: module MyModule is not loaded and could not be found

However, if you would write MyModule.my_function(), the code runs without errors.

So, is it somehow possible to import functions from a dynamically loaded module?

Upvotes: 1

Views: 466

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Elixir is a compiled language and even what has a .exs extension and what is called script, is to be compiled into BEAM before execution.

The issue is import MyModule cannot be compiled because at the moment the compiler knows nothing about this module. The good news is we might fool the compiler.

Put all the code you need into a separate file:

# script.ex

import MyModule
my_function()

and use runner.exs script which will be compiling both:

# runner.exs

Code.eval_file("module.ex")
# IO.inspect Code.ensure_loaded(MyModule)
Code.eval_file("script.ex")

Now runner.exs would happily call my_function().

Upvotes: 4

Related Questions