Andrew Timberlake Andrew Timberlake

Hi, I’m Andrew, a programmer and entrepreneur from South Africa,
building Mailcast for taking control of your email.
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.

Example

defmodule MyApp.IexUtilities do
  def u(id_or_username) do
    MyApp.Users.find_user(id_or_username)
  end
end

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"}

Macros

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))
  end
end

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