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:
- 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} years old.") end end
- Start an IEx session in the same directory where you saved
constants.ex
:> iex constants.ex
Tip
Instead of starting IEx and then loading and compiling...