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
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a simple application


In this recipe, we will be using Mix to create a new application.

How to do it…

To create a new Elixir application, follow these steps:

  1. In a command-line session, enter mix help to see a list of available tasks:

    > mix help
    

    Here is what the screen will look like:

  2. To generate a new application, type mix new simple_app:

    > mix new simple_app
    

    What happens next is shown in the following screenshot:

  3. Inside the simple_app directory, the generated application is ready to be started. Run iex –S mix to start the application and verify that everything is working:

    > iex -S mix
    Erlang/OTP 17 [erts-6.1] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
    Interactive Elixir (0.15.1) - press Ctrl+C to exit (type h() ENTER for help)
    iex(1)>  
    
  4. Nothing happened. So is it working? The absence of messages in the IEx session is a good thing. This generated application behaves more like a library; there's no main function like in Java or C. To be sure that the application is responding, edit the lib/simple_app.ex file by inserting the following code:

    defmodule SimpleApp do
      def greet do
        IO.puts "Hello from Simple App!"
      end
    end
  5. Restart the application by pressing Ctrl + C twice and entering iex –S mix again.

  6. In the IEx session, enter SimpleApp.greet.

  7. You will see the following output from the application:

    iex(1)> SimpleApp.greet
    Hello from Simple App!
    :ok
    iex(2)>
    

The Elixir application is ready to be used either on your local machine or, if a node is started, it could even be used from another machine.

How it works…

The Elixir installation provides a command-line tool called Mix. Mix is a build tool. With this tool, it is possible to invoke several tasks to create applications, manage their dependencies, run them, and more.

Mix even allows the creation of custom tasks.

See also

  • To generate an OTP application with a supervisor, see the Generating a supervised application recipe.