More modules in Elixer

In the post A little more Elixir, we’re talking modules and functions we looked at a basic use of modules to allows us to declare functions (and macros, although we’ve not really touched these yet).

Modules can be nested, for example

defmodule Math do
  defmodule Fractions do
  # Nested module and functions 
  end

  # Top level module an functions
end

These don’t actually have a relationship with one another, instead Elixir essentially has them as separate modules, like this

defmodule Math do
  # functions
end

defmodule Math.Fractions do
  # functions
end

Importing modules

The import keyword (as the name suggests) imports a module’s functions and/or macros into the scope of the module or function they’re imported into. The scope is limited to that defined by the start and end of the module or function. Importing allows us to call functions from the module without having to use it’s module name. For example, we have a Math module with functions add and sub but we import it into our function like this

def f do 
  import Math
  add(1, 7)
end

Notice how the highlighted line does not need to prefix the module name to the function.

We can limit what’s imported using additional syntax where where we have only: or except: to reduce the scope of imports to the minimal, for example we do not need sub in our import so we could write

def f do 
  import Math, only [add: 2]
  add(1, 7)
end

In the above we import only the add function with arity of 2 (i.e. the 2 parameter function named add).

Aliasing modules

As the name suggests, alias allows us to create an alias to a module name, for example let’s say we have Math.Fractions whilst not a big deal to type if we’re typing it for every function it create a lot of “clutter” in our code, so instead we can alias the name like this

defmodule TestMod do
  alias Math.Fraction, as: F
  def f do
    F.some_function()
  end 
end

Require a module

The require keyword ensure the macro definitions of a module are compiled into the scope using the require. Or to put this another way require ensures that a required module is loaded before the module that’s calling into it. This will ensure any macros within it are available to the calling module and they’re scoped to that calling module.

Note: require is not like an alias, so you still need to prefix any macro/function calls with the module name (unless you also alias it ofcourse)

An example might be something like this

defmodule A do
  defmacro hello(arg) do
    quote do
      IO.puts "Hello #{unquote(arg)}"
    end
  end
end

defmodule B do
  def hello_world() do
    A.hello "World"
  end
end

In the above, if you compile this into iex using c(“require_sample.rx”) you’ll get warnings such as warning: you must require A before invoking the macro A.hello/1 if you try to execute the command B.hello_world(“Scooby”) you’ll get an error like this ** (UndefinedFunctionError) function A.hello/1 is undefined or private. However, there is a macro with the same name and arity. Be sure to require A if you intend to invoke this macro.

So as you can see, we need to use require, simply add the require A as below

defmodule A do
  defmacro hello(arg) do
    quote do
      IO.puts "Hello #{unquote(arg)}"
    end
  end
end

defmodule B do
  require A
  def hello_world() do
    A.hello "World"
  end
end

The use macro

The use macros allows us to “inject” any code into the current module. It’s used as an extension point.

I’ll dedicate a post of it’s own to the use keyword as it’s interesting what you can do with it.

Module Attributes

Attributes in Elixir are prefixed with the @ symbol. These add metadata to our module. An attribute is declared as a @name value pair. Whilst the name can be pretty much anything (within the allowable syntax), for example I might have a @my_ver 1, there are some reserved names

  • @moduledoc is use for module documentation
  • @doc is use for function or macro documentation
  • @spec is use to supply a typespec for the function which follows
  • @behaviour is used for OTP or under-defined behaviour (and yes it’s the UK spelling)

Here’s an example of creating our own attribute and we’re able to use it within our functions

defmodule Attributes do
  @some_name PutridParrot

  def attrib() do
    @some_name
  end
end

This will return the @some_name value.

You can set the attribute multiple times within the module scope. Elixir evaluates from top to bottom so functions after a change to the @some_name (above) will get the new value.