Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
adamkgray Avatar asked Mar 30 '18 16:03

adamkgray


People also ask

What is __ module __ In elixir?

__MODULE__ is a compilation environment macros which is the current module name as an atom.


2 Answers

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.

like image 180
Dogbert Avatar answered Oct 16 '22 19:10

Dogbert


The convention is only to name all your modules inside your application/package as MyApp.MyModule (assuming that your application/package is named MyApp.) That is more or less similar to java convention to name packages com.example.blah....

This is done to prevent name clashes between different applications/packages.

Elixir core modules are not namespaced (there are some exceptions like String.Chars, though.)

Inside your application/package it is totally up to you whether to choose the flat model for module naming, or hierarchical.

BTW, the module name might be any valid atom. The dot is the convention only, it affects neither mode accessibility for the compiler nor anything else. Module.concat/{1,2} helper uses dot to build up module names, but again this is the convention only.

like image 21
Aleksei Matiushkin Avatar answered Oct 16 '22 19:10

Aleksei Matiushkin