Codementor Events

Autogenerate Elixir Documentation

Published Oct 15, 2018

In this piece we'll use ExDoc to generate documentation for a simple Fibonacci module.

Elixir's standard documentation module offers quite a bit out of the box. It will automatically generate documentation for your project, including modules, the functions they contain and their arguments even if you don't write any @doc blocks at all.

If you do write @doc blocks, that information gets added and any examples you copy from IEx into those blocks will automatically be run along with your tests when you run mix test!

Full screencast

Add ex_doc to the deps in your Mixfile

defmodule Fib.Mixfile do
  use Mix.Project

  def project do
    [
      app: :fib,
      version: "0.1.1",
      elixir: "~> 1.7",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [extra_applications: [:logger]]
  end

  defp deps do
    [{:ex_doc, "~> 0.19", only: :dev, runtime: false}]
  end
end

Then run mix deps.get to pull in the library.

Now you can auto-generate docs for your app

mix docs will generate documentation with each of your modules and function signatures.

Add module and function documentation

defmodule Fib do
  @moduledoc """
  The `Fib` module provides both fast and slow functions for calculating fibonacci sequence numbers.
  """
  # ...


  @doc """
  `Faster` calculates fibonacci numbers more quickly using tail recursion.
  """
  def faster(n), do: faster(n, 0, 1)
  def faster(1, _acc1, acc2), do: acc2
  # ...

Examples in function docs are tests

  @doc """
  `Faster` calculates fibonacci numbers more quickly using tail recursion.
      iex(1)> Fib.faster(6)
      8
  """

Now each time you run mix test, the Fib.faster(6) will be executed. If the return value is not 8, you'll have a failing test.

Notice that if you copy paste a working example from one function to another, as in the end of this video, your doc tests will still pass. They don't yet require that the function being documented is actually used in the example... could this be an opportunity to contribute to ExDoc?

Originally published at https://alchemist.camp/episodes/generate-elixir-docs

Discover and read more posts from Mark Wilbur
get started
post commentsBe the first to share your opinion
Show more replies