Rodrigo Martins

I'm a Catholic Christian, software developer, Passionate about life, codes, questions, theories and theorems. :)

[Elixir] Reload on Iex

| Comments

Hi,

After version 1.2.x of Elixir, we have in IEx.Helpers module the recompile function.

My problem is:

Detail: I’m using Phoenix framework. I have a User module, but without constant the genres. I need a constant the genre with male and female gender. When start the console with: iex -S mix phoenix.server, I see that it lacked the constant of the genres, and it will be very laborious every time that you have any changes in the code you have to drop the iex and raise again to recompile everything again.

Searching found some monkey patches to solve this, but the elixir already has it native. And it’s beautiful not to have this job.

When you have to make change and the iex already started, just call the recompile function.

Example:

User
1
2
3
4
5
6
# Module without constant
defmodule Sample.User do
  use Sample.Web, :model
  use Coherence.Schema

end

Start iex -S mix phoenix.server

iex
1
2
3
iex(6)> User.genres
** (UndefinedFunctionError) function Sample.User.genres/0 is undefined or private
    (savepass) Sample.User.genres()

I change User module:

User
1
2
3
4
5
6
7
8
9
10
11
12
# Module with constant
defmodule Sample.User do
  use Sample.Web, :model
  use Coherence.Schema

  @sex_kind %{
    male: "Male",
    female: "Female"
  }

  def genres, do: @sex_kind
end

I do not leave the iex console, then I run recompile:

iex
1
2
3
iex(6)> recompile
Compiling 1 file (.ex)
:ok

And then just call the function that takes the constants.

iex
1
2
iex(7)> User.genres
%{female: "Female", male: "Male"}

Thanks!

Comments