Andrew Timberlake Andrew Timberlake

Hi, I’m Andrew, a programer and entrepreneur from South Africa, founder of Sitesure for monitoring websites, APIs, and background jobs.
Thanks for visiting and reading.

Add utility functions to iex

Elixir has some useful utility functions available in iex like h/1 which prints documentation on the given module or function/arity pair.

You can add your own utility functions or macros by defining a utility module and then importing it into your .iex file.


defmodule MyApp.IexUtilities do
  def u(id_or_username) do

Import your utility module in your .iex file in the project root

# .iex
import MyApp.IexUtilities

and the function is available in your iex session

iex> user = u "demo"
%MyApp.User{id: 42, username: "demo", name: "John Doe"}


You can take this a bit further and automatically assign it to a variable within the iex session by using a macro and an unhygienic variable. The variable defined with var!/1 will bleed out to the outer scope meaning you can type u "username" and have the result automaitcally added to a variable, in this case user;

defmodule MyApp.IexUtilities do
  defmacro u(id_or_username) do
    var!(user) = MyApp.Users.find_user(unquote(id_or_username))

and now in your iex session you can easily lookup a user to work with.

iex> u "demo"
%MyApp.User{id: 42, username: "demo", name: "John Doe"}
iex> user
%MyApp.User{id: 42, username: "demo", name: "John Doe"}
2 Aug 2023