Creating Custom Mix Tasks

Developers write tasks all the time to handle repetitive behavior (once a week parsing of large CSV files) or even for fun (making a random die roller to play Dungeons and Dragons with). Here, we cover how to write a custom mix task to accomplish just that.

We should be able to run a command like the following to emulate rolling a d100:

mix die_roller 100

Let’s create a mix app and associated task file

mix new custom_mix

mkdir -p lib/mix/tasks && touch lib/mix/tasks/die_roller.ex

In lib/mix/tasks/die_roller.ex let’s write a task module with a run function, which will get called after we compile and run the mix task.

defmodule Mix.Tasks.DieRoller do
  use Mix.Task

  def run(_args) do
    IO.puts “Die Roller runs”
  end
end
mix compile
mix die_roller
Die roller runs

We’ll also need to add a @shortdoc to the file in order to see the task and its description in mix help.

A few things to note here. The arguments the mix task receives get parsed as a list of strings. So, mix die_roller 4 provides the run function with an argument of [“4”]

Because of that, we need to do a little pattern matching and string to integer conversion for our random number generator to work.

defmodule Mix.Tasks.DieRoller do
  use Mix.Task
  @shortdoc "Runs die roller"

  def run(args) do
    [number | _] = args
    num = String.to_integer(number)
    roll = Enum.random(1..num)

    IO.puts "You rolled a #{roll} on a d#{num}"
  end
End

If we compile and run mix die_roller 100, we have a nifty d100 emulator now!

Sign up for our newsletter

Get notified of any new episodes as we release them.

© 2020 QuantLayer, LLC. All rights reserved.