O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Note

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.") end @name "Joe" def function_two do IO.puts("#{@name} is #{@age+1} ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required