Elixir modules each have associated metadata. Each item of metadata is called an attribute of the module and is identified by a name. Inside a module, you can access these attributes by prefixing the name with an at sign (@). You give an attribute a value using the syntax
| @name value |
This works only at the top level of a module—you can’t set an attribute inside a function definition. You can, however, access attributes inside functions.
| defmodule Example do |
| @author "Dave Thomas" |
| def get_author do |
| @author |
| end |
| end |
| IO.puts "Example was written by #{Example.get_author}" |
You can set the same attribute multiple times in a module. If you access that attribute in a named function in that module, the value you see will be the value in effect when the function is defined.
| defmodule Example do |
| @attr "one" |
| def first, do: @attr |
| @attr "two" |
| def second, do: @attr |
| end |
| IO.puts "#{Example.second} #{Example.first}" # => two one |
These attributes are not variables in the conventional sense. Use them for configuration and metadata only. (Many Elixir programmers employ them where Java or Ruby programmers might use constants.)