#203: .iex.exs File
Follow along with the episode starter on GitHub
https://hexdocs.pm/iex/IEx.html#module-the-iex-exs-file
When working in development on an application, you’ll often use IEx - Elixir’s interactive shell. In fact, let’s start up a session right now with our Teacher
application. Our application has a function we can use - Teacher.Recordings.get_album!
- that returns an album.
$ iex -S mix
> Teacher.Recordings.get_album!(1)
...
This works, but every time we call it here we have to include the Teacher
prefix, unless we alias it first. It would be great if could alias or even import the different modules we want, automatically, each time we start an IEx session. Luckily for us - we can do just that with the .iex.exs
file.
When you start an IEx session, it looks for a file called .iex.exs
in your current working directory and runs it. This is great because it saves you from having to type the same setup commands over and over.
Let’s add one to our application. We’ll go to our application and add a new file called .iex.exs
. Then inside it we’ll just add whatever setup we want to happen when we start an IEx session.
Let’s add alias Teacher.Repo
. We can import Ecto.Query
, alias Teacher.Recordings
, and add an alias for our Album
and Artist
schema modules. Then let’s include a message that will be displayed when we start a new IEx session. This is a nice reminder of what we set up.
# .iex.exs
alias Teacher.Repo
import Ecto.Query
alias Teacher.Recordings
alias Teacher.Recordings.{Album, Artist}
IO.puts "Teacher IEx helpers loaded (Repo, Recordings, Album, Artist)"
With that done, let’s go back to the command line and start another IEx session with our application. And great - We see our message is displayed!
$ iex -S mix
Teacher IEx helpers loaded (Repo, Recordings, Album, Artist)
Now before we had to include the prefix for Recordings.get_album!
, but with our .iex.exs
file we should be able to remove that. It still works - our album was returned.
# Teacher.Recordings.get_album!(1)
> Recordings.get_album!(1)
...
Now if we needed to get all albums, instead of including all prefixes like this we can simplify this quite a lot, which is great for development.
# Teacher.Repo.all(Teacher.Recordings.Album)
> Repo.all(Album)
...
And because we imported Ecto.Query, it’s easy to write and test queries from IEx - let’s try test it out and return all albums we have in the database after the year 1972.
> Album |> where([a], a.year > 1972) |> Repo.all()
...
The .iex.exs
file transforms IEx from a basic console, allowing you customize your IEx sessions to speed up development.