Search code examples
elixir

How do you import a custom module defined in another file?


a.exs:

defmodule A do
  def greet, do: IO.puts "hello"
end

b.exs:

defmodule B do
  import A
  def say_hello, do: greet
end

Result:

~/elixir_programs$ iex b.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

** (CompileError) b.exs:2: module A is not loaded and could not be found

~/elixir_programs$ tree .
.
├── a.exs
├── app1.exs
├── b.exs
....

For that matter, how do you use the qualified name to call a function defined in another module:

b.exs:

defmodule B do
  def say_hello, do: A.greet
end

~/elixir_programs$ iex b.exs
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> B.say_hello
** (UndefinedFunctionError) function A.greet/0 is undefined (module A is not available)
    A.greet()

Okay, this works:

iex(1)> c "a.exs"
[A]

iex(2)> B.say_hello
hello
:ok

Solution

  • This works:

    Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
    iex(1)> c "a.exs"
    [A]
    
    iex(2)> c "b.exs"
    [B]
    
    iex(3)> B.say_hello
    hello
    :ok
    
    iex(4)>