Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Using module directives

To simplify working with modules, Elixir provides three directives: import, alias, and require. These three module directives are lexically scoped—if defined in the module scope, they are valid for the whole module, but if defined inside a function, they are only valid inside that function.

These three directives allow the use of code defined in other modules.

Getting ready

Create the require_me.ex file with the following content:

defmodule RequireMe do
  def foo do
    IO.puts "This is foo from #{__MODULE__} module"

In the same folder, create the directives.ex file and add the following code:

defmodule Directives do
  @col  [1,2,3]
  @name "demo"

  # require directive

  # alias directive module scope
  alias String, as: S
  # import directive module scope
  import List, only: [first: 1]

  def test_module_alias do
    IO.puts "Name is #{S.capitalize(@name)}"

  def test_function_alias do
    # alias directive function scope
    alias RequireMe, as: RM...