vmoravec
vmoravec

Reputation: 93

How to define functions in iex main scope?

In file ~/.iex.exs I have a module defined with several functions and I want to call those functions from iex shell without the module name prefix.

Using import SomeModule does not work, I'm getting error: module SomeModule is not loaded but was defined. This happens because you are trying to use a module in the same context it is defined. Try defining the module outside the context that requires it.

Is there some way of doing this in the ~/.iex.exs?

Upvotes: 5

Views: 1046

Answers (2)

Daniel Franklin
Daniel Franklin

Reputation: 46

import SomeModule is supported in recent versions.

.iex.exs:

defmodule IexHelpers do
   def foo, do: :foo
end

import IexHelpers

Upvotes: 1

whatyouhide
whatyouhide

Reputation: 16781

This is a known limitation of the .iex.exs mechanism. The .iex.exs file is evaluated in the same context as the one you type stuff in in the shell: basically, IEx loads the .iex.exs just as if you typed it in the shell.

In Elixir, you can't define a module and import it in the same context (e.g., you can't define a module in the shell/in a file and import it thereafter) and that is what is happening there.

My advice is: define the module in .iex.exs and alias it (still in .iex.exs) to a very short name. For example, in .iex.exs:

defmodule MyModule do
  def foo, do: :foo
end

alias MyModule, as: M

Then, in the shell:

iex> M.foo
:foo

It's not optimal but right now, it's a possible compromise.

Upvotes: 5

Related Questions