How to use mix aliases to run custom project-specific tasks

August 4, 2017

The Problem

Everytime you want to do one thing in an elixir project you have to type more than one thing.

For Example

If you want to clear out a database and put some dummy data in it, you have to run four things!

$ mix ecto.drop
$ mix ecto.create
$ mix ecto.migrate
$ mix run priv/repo/seeds.exs

What a hassle.

The Solution

Mix aliases. Mix is an amazing tool and a big reason I love working with Elixir so much. One of the many things it does is run tasks for you (like rake in ruby).

If there’s something you want to do that requires many steps, you can tell mix all the instructions and give them a name so that you’ll only have to type one thing.

If you work with Phoenix, you’ll see some already set up for you in mix.exs:

defp aliases do
    "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
    "ecto.reset": ["ecto.drop", "ecto.setup"],
    "test": ["ecto.create --quiet", "ecto.migrate", "test"]

This way you only have to type mix ecto.reset, and you can forget about what steps you have to do in what order to get your local db back into a normal state.

These are specific to your project, so you can go crazy without adding a bunch of project-specific aliases to you bash or zsh profile.