Start Learning Elixir in Five minutes

Elixir is a dynamic and functional Ruby like language. It runs on the Erlang VM, making it highly suited to applications that need to be massively scalable and fault tolerant.

What you can make with Elixir

  • Fast webapps that are Ruby like
  • Things that need massive concurrency like:
    • message brokers (the big rabbit of message brokers, RabbitMQ is written in Erlang)
    • chat apps
    • gaming sites

How to get Elixir

On macOS run:

$ brew install elixir

On Ubuntu run:

$ wget && sudo dpkg -i erlang-solutions_1.0_all.deb
$ sudo apt-get update
$ sudo apt-get install esl-erlang
$ sudo apt-get install elixir

On Arch run:

$ sudo pacman -S elixir

On Windows download the installer

How to make things with Elixir

First things first, let's run some code. Run the following to open up an elixir repl:

$ iex

Then run a hello world:

iex(1)> "hello" <> " world"
"hello world"

How to make a Webapp With Elixir

We outputted a string, so now let's output that string on an http port, like a real developer.

First generate a new project using mix:

$ mix new hello_elixir
$ cd hello_elixir

Open your mix.exs and change the deps block to be like this:

defp deps do
  [{:cowboy, "~> 1.1.2"},
   {:plug, "~> 1.3.4"}]

And the application block to this:

def application do
    applications: [:cowboy, :logger, :plug],
    mod: {HelloElixir, []}

We are going to be using Plug and Cowboy. Cowboy is a webserver and Plug is an API similar to Rack or WSGI. Run $ mix deps.get to install the new dependencies.

Now we are going to create our first Plug module, create a new file called lib/hello_world_plug.ex:

defmodule HelloElixir.HelloWorldPlug do
  import Plug.Conn

  def init(options), do: options

  def call(conn, _opts) do
    |> put_resp_content_type("text/plain")
    |> send_resp(200, "Hello from Elixir!")

Plug modules must implement two functions init and call. init gets called when the app boots and call gets called on every request. Now we need to run this Plug module open lib/example.ex and change it to:

defmodule HelloElixir do
  use Application
  require Logger

  def start(_type, _args) do
    children = [
      Plug.Adapters.Cowboy.child_spec(:http, HelloElixir.HelloWorldPlug, [], port: 8080)
    ] "Started application"

    Supervisor.start_link(children, strategy: :one_for_one)

We are now ready to run our app! Let's run it:

$ mix run --no-halt

You should see a bunch of stuff like:

===> Compiling cowboy
==> mime
Compiling 1 file (.ex)
Generated mime app
==> plug
Compiling 44 files (.ex)
Generated plug app
==> hello_elixir
Compiling 2 files (.ex)
Generated hello_elixir app

Open up localhost:8080. It should say

Hello from Elixir!

That is it! You are an Elixir programmer now!