Elixir Series

Versions

Module Basics

Define a Module

To define a module we use the defmodule macro, followed by the module name and a do block.

defmodule Math doend

Modules use the CamelCase convention in which each word is capitalized with no spaces or underscores.

Modules must also have unique names.

Module File Naming

File names for Elixir modules also follow the snake_case convention. For example, the Math module should, by convention live in the math.ex file.

You'll likely need to nest some modules inside other namespaces such as with "contexts" in the Phoenix Framework.

In this case, if Accounts is the context and User is the module, you'd expect to have an "accounts" directory with the file "user.ex":

- accounts |- user.ex

File Extensions

You've probably seen .ex and .exs extensions mentioned in your Elixir journey. The difference is important so I thought it would be good to touch on here.

When executed, both file extensions will compile and load their modules into memory.

Elixir treats both files exactly the same way, the only difference being that .ex files are compiled to bytecode on disk as .beam files. .exs files are not, and therefore more suitable for scripting as interpreted code.

ExUnit tests are a good example of when it makes sense to use .exs files.

Because they're interpreted, you don't have to recompile every time you make a change to your tests.

Module Attributes

Module attributes are defined using the @ symbol. Let's use some examples to see how they're used.

As Annotations

They can annotate a module with information about how to use the module:

Elixir Series

Connect

I hope you're finding this series helpful. If you find any issues or have any feedback feel free to hit me up on twitter: @tmartin8080 || @phxroad or subscribe to the mailing list to receive occasional updates.