Search code examples
elixirelixir-mix

When to use a dot in elixir module name?


I have seen elixir modules named this way:

defmodule Foo.bar.baz do
end

But I can't find any documentation stating when to do this.

Does it have to do with subdirectories? Using mix, I can put my modules in subdirectories within the lib folder, and they work fine without dots.

For example:

# this is in /lib/foo/bar

defmodule Bar do
end

What is the convention?


Solution

  • There's nothing special about .. You can give a module any name you want as long as it's a valid atom, including e.g. whitespace:

    iex(1)> defmodule :"hello world!!!" do
    ...(1)>   def hi, do: :ok
    ...(1)> end
    iex(2)> :"hello world!!!".hi
    :ok
    

    You're also not required to name the modules the same as the file/folder they're in. You can define any module in any .ex file inside lib and they'll be available to the whole application and iex.

    The convention, if a file declares a single module at the top level, is to name it based on its path, excluding lib, converting each path segment to capital case. For example, lib/foo/bar/baz.ex usually defines a module named Foo.Bar.Baz.