Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Using module attributes as constants

Elixir supports the definition of module attributes using the @ syntax. There are a few reserved module attributes: @moduledoc, @doc, @behaviour, and @before_compile. We will focus on some of them in the next two recipes.

In this recipe, we will use module attributes as constants and access them inside functions.


Module attributes can only be defined outside functions and can be defined more than once in a module.

How to do it…

To use module attributes as constants, follow these steps:

  1. Create a new constants.ex module and add the following code:

    defmodule Constants do
      @name "Bill"
      @age 22
      def function_one do
        IO.puts("#{@name} is #{@age} years old.")
      @name "Joe"
      def function_two do
        IO.puts("#{@name} is #{@age+1} years old.")
  2. Start an IEx session in the same directory where you saved constants.ex:

    > iex constants.ex


    Instead of starting IEx and then loading and compiling the module, it is possible to indicate the name...