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
?
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.