Pete's Alley - Elixir Macros

Written by Rich Morin.

Contents: (hide) (show)

Path:  AreasContentOverviews

Precis:  use of Elixir macros in Pete's Alley

The Elixir programming language supports hygienic macros (an enhanced form of syntactic macros). Pete’s Alley employs very few macros, at present.

__using__(which)

This macro comes along as part of Phoenix. It is used to dispatch to the appropriate controller, view, etc.

defmacro __using__(which) when is_atom(which) do
  apply(__MODULE__, which, [])
end

__using__(_)

We use a lot of compound data types (e.g., trees of maps, with atoms as keys and strings as leaf values). Dialyxir lets us document these and check their usage. However, keeping our @spec attributes tidy means that we need to define a lot of @type attributes. And, in order to keep our code DRY, we need to define these in one place and use them everywhere.

Because attributes aren’t brought in by import, we need another way to make them available. A macro-based hack (adapted from this posting) lets us do this by means of use <Module>.Types. For example:

defmodule Common.Types do
  ...
  defmacro __using__(_) do
    quote do
      # An item is a tree of maps, with strings at the leaves.

      @type item        :: %{ map_key => item_part }
      @type item_part   :: %{ map_key => item_part | String.t }
      ...
    end
  end
end