Elixir Elm Tutorial Sample
Elixir Elm Tutorial Sample
Bijan Boustani
This book is for sale at http://leanpub.com/elixir-elm-tutorial
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Were Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Who Is This Book For? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Why Elixir and Elm? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Technology Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Diving In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Note on Phoenix Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Creating the Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Configuring the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Running the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Our First Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Running a Migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Creating Players . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Updating our Home Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Writing Elixir Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Current Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Appendix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Quick Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Working with Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Introduction
Welcome to the world of functional web programming! In this book, well learn how to create fun,
scalable, and maintainable web applications. Well be using a wide range of web technologies
along with the latest ideas from emerging languages like Elixir and Elm to craft a fun experience.
Rather than focusing on theory, well take a practical approach and build a real-world application.
Acknowledgements
I would like to thank Envy Labs and Code School for fostering an environment where Ive been able
to work hard and learn and grow. Id also like to thank Jos Valim and Evan Czaplicki for crafting
such beautiful and fun languages. Thanks to Michael Hartl for setting the standard for technical
writing with The Ruby on Rails Tutorial, and Bret Victor for inspiring all of us with his visions of
the future.
The material in this book is intended to be crafted in such a way that you can follow along simply
by typing in the relevant code examples. Beginners can still learn a lot simply by following along
and building the application, because sometimes in programming you need to be exposed to certain
concepts and ideas before they become easy to understand. The experience of building something
will be fun and engaging; and a deeper understanding will follow with increased familiarity and
experience.
Prerequisites
In addition to the notes above about the intended audience for this book, here are some additional
prerequisites to keep in mind:
Elixir
Elixir3 is a dynamic, functional language designed for building scalable and maintainable applica-
tions.
Elixir is built on top of the Erlang virtual machine, and therefore inherits decades worth of
stability and scalability.
Concurrency is at the heart of Elixir. Instead of getting faster processors, computers these days
are getting processors with more cores. That means we need to write our programs in such a
way that allows them to be distributed across multiple cores so our programs can outperform
our competitors. As an example, compare the latest 13-inch Macbook Pro models4 with dual-
core processors with 15-inch Macbook Pro models5 with quad-core processors. Then, see how
many cores youll have access to when you deploy your application to a multi-core web
server6 .
1
https://pragprog.com/book/elixir/programming-elixir
2
https://guide.elm-lang.org
3
http://elixir-lang.org
4
http://www.apple.com/shop/buy-mac/macbook-pro/13-inch
5
http://www.apple.com/shop/buy-mac/macbook-pro/15-inch
6
https://www.digitalocean.com/pricing/#droplet
Introduction 3
The Phoenix web framework provides us with the ability to create new projects quickly. For
web developers that have worked with Ruby on Rails, the concepts will be familiar and easy
to pick up.
Elixir also inherits amazing features from other languages:
Rubys readable syntax and philosophy of developer happiness.
Erlangs stability and scalability.
F#s magical pipeline operator for data transformation.
LISPs macros and metaprogramming.
Elm
Elm7 is an exciting new functional language that is still evolving. Its the fastest, most reliable front-
end web programming language currently available.
Technology Stack
There are many technologies involved in building and deploying modern web applications. Well
be using a straightforward stack of technologies that will allow us the flexibility to scale our
applications gracefully. Heres the short version of the technology stack:
Back-end: Elixir
Front-end: Elm
These technologies stand on the shoulders of giants, so heres a little more information about other
technologies well also use while building our applications:
Functional Programming
If youre coming from a background in working with Ruby on Rails or JavaScript web frameworks,
then youll have a head start in being able to grasp the content and move smoothly through the book.
Something to keep in mind is that Elixir and Elm are functional languages. If youre coming from an
object-oriented background, you may find some of the programmatic approaches to be unfamiliar
at first, but the initial discomfort will pay off in the long run as you learn to solve problems in an
elegant functional manner.
Summary
In this introduction, we touched briefly on the application well be building and some of the
reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these
technologies and experiencing the benefits first-hand, so lets dive in and start building our
application in the next chapter.
Diving In
Instead of simply reading about Elixir and Elm, lets dive in and experience what these languages
have to offer. In this chapter, were going to avoid detailed explanations and theory in favor of
quickly building the foundation for our project. Well focus on running the right console commands
and writing the code well need to start creating our application.
Later in the book, well cover more about the fundamentals of Elixir, but for now lets focus on
following along and getting a glimpse of how to get an application up and running. If you havent
already set up your development environment with Elixir, Phoenix, and PostgreSQL, then check out
the Appendix in the back of the book for more information.
43 * creating platform/assets/static/images/phoenix.png
44 * creating platform/assets/static/favicon.ico
45
46 Fetch and install dependencies? [Yn] Y
47 * running mix deps.get
48 * running mix deps.compile
49 * running cd assets && npm install && node node_modules/brunch/bin/brunch build
50
51 We are all set! Go into your application by running:
52
53 $ cd platform
54
55 Then configure your database in config/dev.exs and run:
56
57 $ mix ecto.create
58
59 Start your Phoenix app with:
60
61 $ mix phx.server
62
63 You can also run your app inside IEx (Interactive Elixir) as:
64
65 $ iex -S mix phx.server
Notice that Phoenix displays a lot of helpful information. First, the output shows all the files that
were generated (dont worry if it seems overwhelming at first; were only going to start with a
handful of these files). Then, we see some information about how to configure our database and
start the server.
1 $ cd platform
We can set up the database for our project by running the following command:
1 $ mix ecto.create
Diving In 8
If you run into issues here, it likely means youll have to configure your PostgreSQL installation or
adjust the database username and password fields at the bottom of the config/dev.exs file. You can
also check out the Appendix at the back of this book for more information on PostgreSQL.
Since this is the first time were running a command with our new application, well see that it takes
time for the source code to compile. Elixir is based on the Erlang virtual machine, and needs to
compile the source to bytecode before we can run our programs. Dont worry if this seems to take
a while at first, because subsequent commands will run much more quickly after this.
If the database creation was successful, well see the following message at the bottom:
1 $ mix ecto.create
2 Compiling files (.ex) ...
3 Generated platform app
4 The database for Platform.Repo has been created
We have successfully created our Phoenix application, compiled it, and set up our database.
1 $ mix phx.server
This will start a server and allow us to visit http://0.0.0.0:40008 in a browser to see our new
application running. Here is what the output will look like:
1 $ mix phx.server
2 [info] Running PlatformWeb.Endpoint with Cowboy using http://0.0.0.0:4000
8
http://0.0.0.0:4000
Diving In 9
At this point, you might be impressed that we managed to get a full back-end up and running so
quickly. Or you might have seen similar features in other frameworks and youre nonplussed with
our progress so far. Were going to start adding features to our application, but its worth taking a
moment to appreciate just how much we already have going for us with just a few commands.
Feel free to take a look at some of the great documentation listed on the default Phoenix start page.
Before we move on, lets stop the Phoenix web server. Go back to the Terminal where the server is
running, and press Control + C on your keyboard twice to stop the server. This is what the output
will look like as you return from the running web server to a blank command line:
Diving In 10
1 $ mix phx.server
2 [info] Running Platform.Endpoint with Cowboy using http://0.0.0.0:4000
3 [info] Compiled 6 files into 2 files, copied 3 in 2.1 sec
4 [info] GET /
5 [debug] Processing by PlatformWeb.PageController.index/2
6 Parameters: %{}
7 Pipelines: [:browser]
8 [info] Sent 200 in 67ms
9 ^C
10 BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
11 (v)ersion (k)ill (D)b-tables (d)istribution
12 ^C
13 $
Players
Games
Were going to start by using something called a generator to keep moving quickly. Its going to
create a lot of the files we need to work with. Then, well cover more about how it all works later.
Lets generate the resource for our players with the following command:
With this command, were creating players for our game platform. We want to be able to use
our browser to interact with the data, so were starting with phx.gen.html9 to generate an HTML
resource.
Because were creating player accounts for our application, we use Accounts to provide a context
for our resource. Then, we use Player for the module name and players to indicate the pluralized
form, which will also be used to create the database table.
For the player fields, each player account will have a username (stored as a string), and a score
(stored as an integer). Well eventually extend the capabilities of our players with additional fields,
but for now this will give us a good starting point to start creating a list of players.
Youll see that the generator creates quite a few files for us, and once again Phoenix gives us some
helpful tips about what to do next:
9
https://hexdocs.pm/phoenix/Mix.Tasks.Phoenix.Gen.Html.html
Diving In 11
Routing
Dont worry too much about all those files yet, but the information at the bottom is important. In
order to configure our application to work with our new player accounts, well need to add them to
the router first, and then run a migration to update the database with a new players table.
Phoenix makes things easy on us with the helpful notes in the Terminal. Lets go ahead and follow
along. Open the lib/platform_web/router.ex file and see what it looks like:
1 defmodule PlatformWeb.Router do
2 use PlatformWeb, :router
3
4 pipeline :browser do
5 plug :accepts, ["html"]
6 plug :fetch_session
7 plug :fetch_flash
8 plug :protect_from_forgery
9 plug :put_secure_browser_headers
Diving In 12
10 end
11
12 pipeline :api do
13 plug :accepts, ["json"]
14 end
15
16 scope "/", PlatformWeb do
17 pipe_through :browser # Use the default browser stack
18
19 get "/", PageController, :index
20 end
21
22 # Other scopes may use custom stacks.
23 # scope "/api", PlatformWeb do
24 # pipe_through :api
25 # end
26 end
The Phoenix router comes with two separate pipelines by default. One of them is for HTML (which
were going to use now), and the other one is for JSON (which well also use later). And we can even
see that the scope is already set up for us to access the HTML with our browser. Thats how we were
able to load the http://0.0.0.0:4000 URL and see the initial starter page. Dont worry if it seems
confusing at first. All you need to know is that this block of code is where well focus for now:
That means when we access http://0.0.0.0:4000/players10 , well soon be able to start creating
the players for our game platform.
10
http://0.0.0.0:4000/players
Diving In 13
Running a Migration
Our application has all the information it needs to render the players resource that we created, but
we still need to tell the database about the changes that we made. For the database to store our player
data (with the username and score fields), well need to run a migration. Go back to the Terminal,
and run the following command:
1 $ mix ecto.migrate
This will create a new database table called players. If everything goes according to plan, then we
should see the following output:
1 $ mix ecto.migrate
2 Compiling 10 files (.ex)
3 Generated platform app
4 08:18:44.181 [info] == Running Platform.Repo.Migrations.CreatePlayers.change/0 \
5 forward
6 08:18:44.182 [info] create table players
7 08:18:44.371 [info] == Migrated in 0.1s
Creating Players
Lets start our server again and see our new player resource in action:
1 $ mix phx.server
This is excellent. We can now add players to our platform using a web browser. Click the New
Player link at the bottom and try creating a player on the http://0.0.0.0:4000/players/new12
page.
12
http://0.0.0.0:4000/players/new
Diving In 15
When we successfully create a new player account, well see the show page with the individual
players data (notice the player id number is displayed in the URL too):
Diving In 16
Feel free to create some more player accounts so we have some data to work with on our players
page:
Diving In 17
13
http://0.0.0.0:4000
Diving In 18
1 <div class="jumbotron">
2 <h2><%= gettext "Welcome to %{name}!", name: "Phoenix" %></h2>
3 <p class="lead">A productive web framework that<br />does not compromise speed
4 and maintainability.</p>
5 </div>
6
7 <div class="row marketing">
8 <div class="col-lg-6">
9 <h4>Resources</h4>
10 <ul>
11 <li>
12 <a href="http://phoenixframework.org/docs/overview">Guides</a>
13 </li>
14 <li>
15 <a href="https://hexdocs.pm/phoenix">Docs</a>
16 </li>
17 <li>
18 <a href="https://github.com/phoenixframework/phoenix">Source</a>
19 </li>
20 </ul>
21 </div>
22
23 <div class="col-lg-6">
24 <h4>Help</h4>
25 <ul>
26 <li>
27 <a href="http://groups.google.com/group/phoenix-talk">Mailing list</a>
28 </li>
29 <li>
30 <a href="http://webchat.freenode.net/?channels=elixir-lang">#elixir-lang
31 on freenode IRC</a>
32 </li>
33 <li>
34 <a href="https://twitter.com/elixirphoenix">@elixirphoenix</a>
35 </li>
36 </ul>
37 </div>
38 </div>
This should look familiar in that its mostly comprised of standard HTML code. Its the HTML that
were seeing when we load http://0.0.0.0:400014 . Lets delete this code and create a couple of
14
http://0.0.0.0:4000
Diving In 19
simple links to our player pages. First, remove all the existing code in the lib/platform_web/tem-
plates/page/index.html.eex file. Then, replace it with the following:
Save the file and go back to the browser to see the changes (make sure the Phoenix web server is
still running or restart the server with mix phx.server) at http://0.0.0.0:400015 :
Phoenix comes with a Live Reload feature that automatically refreshes our application in the
browser. If the Phoenix server was still running, then the home page was automatically regenerated
and should now display the buttons that we created. Try them out, and they should enable users to
successfully navigate to the player pages in our application.
Since were working with a .eex file, that means we can embed Elixir code by surrounding it with
tags like this: <%= ... %>. The Elixir code that we put inside those tags will be evaluated, and then
rendered onto the page.
A helpful debugging technique while working with Elixir is to use the IO.inspect17 function to
display results. In this example, were using the IO module with the inspect function, and were
passing it the string "Hello World!":
Embedded Elixir
We can do something similar to embed a link on our page. We wont need to explicitly mention the
module (Phoenix.HTML.Link), because we already have access to some helpful Phoenix functions in
this context. We can recreate our existing HTML links with the following code by passing the link
text, the location, and some extra classes for Bootstrap (which comes preloaded with Phoenix by
default) to make it look nice:
17
https://hexdocs.pm/elixir/IO.html#inspect/2
Diving In 21
We can now verify that our links still work the same way they did previously:
Summary
In this chapter, we managed to cover a lot of ground. We were able to create the entire foundation
for our application with a Phoenix back-end. We leveraged the Phoenix generators to create our
players resource. We also started getting an idea of what the Phoenix folder structure looks like, and
started editing files. We also learned a little about routing and worked with the database.
Weve gotten an introductory look at how to create a full Elixir and Phoenix web platform, and we
even created a couple of player records that we can use as we continue building. But we moved
quickly through these steps, and we dont have a solid understanding of how all these pieces fit
together yet. In the next chapter, well delve into some Elixir basics. And instead of using generators
like we did in this chapter, well manually create features in our application so we can continue
increasing our experience.
Current Outline
Keep in mind that this is a very early version of the Elixir and Elm Tutorial! This outline is an attempt
to break down all the topics and concepts that are covered throughout the book. The structure and
content is a work in progress.
Introduction
Metadata about Elixir, Elm, and functional programming.
Prerequisites and acknowledgements.
Information about the demo application.
Diving In
Quick-paced practical introduction to the Phoenix framework.
Building the initial Platform demo application.
Configuring the PostgreSQL database, running the server, and routing.
Generating the HTML resources for players.
Elixir Introduction
Create a temporary Elixir application to compare of Elixir and Phoenix projects.
Brief background on mix, folder structure, modules, functions, documentation, tests, and
interactive environment.
Introduction to concepts on piping, arity, pattern matching, and guards.
Phoenix Testing and Deployment
Running Phoenix tests.
Working with Git and GitHub.
Configuring the application and deploying to Heroku.
Phoenix Sign Up
Extending existing resources with new fields.
Generating and running migrations.
Basic queries with IEx.
Updating templates and working with forms.
Phoenix Authentication
Importing Hex dependencies.
Working with changesets.
Building an authentication plug.
Adding login and session features.
Database seeds.
Phoenix API
Generating a JSON API for games.
Routing and scopes.
Current Outline 23
Movement (Incomplete)
Implementing character velocity and updating keyboard interaction.
Adjusting directional changes and assets.
Adding character running and jumping abilities.
Changing Levels (Incomplete)
Cursory introduction to game theory and design.
Switching from randomness to pattern recognition.
Adding gradual player skill progression.
Implementing level advancement and final success state.
Syncing Score Data (Coming Soon)
Getting started with Phoenix channels.
Configuring elm-phoenix-socket.
Games (Coming Soon)
Switching away from hard-coded game approach.
Allowing for more extensible game creation and access with API.
Starting implementation for a second game example.
Chat Feature (Time Permitting)
This chapter may be added only if time allows.
Using Phoenix channels to add a chat lobby for players.
Score Data (Time Permitting)
This chapter may be added only if time allows.
Using GenServer to extract score feature into small service.
Appendix
Brief installation instructions.
Contact
Congrats and plea for feedback and ideas.
Bonus access to Slack for live help or sharing.
Appendix
Quick Install
This book is intended for developers with some previous experience, so installing these languages
and tools shouldnt be overly difficult or time-consuming. Having said that, its easy to get tripped
up with installation and configuration steps, so feel free to create a GitHub Issue18 if you think theres
an easier approach to setting things up.
The intention for this chapter is that we want to get everything well need installed quickly so we
can start creating Phoenix projects.
These instructions assume that youre running OS X, but instructions can also be found online for
installing these tools on Linux.
Elixir
First, lets install Elixir19 with Homebrew20 . This command will also install the latest version of
Erlang21 as a dependency:
You can verify that Elixir has been installed properly by running the following command:
1 $ elixir -v
2 Erlang/OTP 20
3 Elixir 1.5
Any trouble with this step? Check out the Elixir install page22 or the Elixir section of Stack
Overflow23 .
Hex
Hex24 is the package manager for the Elixir and Erlang ecosystems. Once you have Elixir installed,
its easy to install Hex with the following command:
18
https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues
19
https://elixir-lang.org/
20
https://brew.sh/
21
https://www.erlang.org/
22
https://elixir-lang.org/install.html
23
https://stackoverflow.com/questions/tagged/elixir
24
https://hex.pm
Appendix 26
1 $ mix local.hex
Any trouble with this step? Check out the Hex section of Stack Overflow25 .
Phoenix
Phoenix26 is a web application framework built with the Elixir language. You can install the latest
version with the following command:
You can verify that Phoenix has been installed properly by running the mix help command, and
you should be able to see a mix phx.new task that will allow us to create new Phoenix applications.
Any trouble with this step? Check out the Phoenix installation docs27 or the Phoenix section of Stack
Overflow28 .
PostgreSQL
Well be using PostgreSQL29 for our database. The easiest way to get started if youre new to
PostgreSQL is to use Postgres.app30 . Its an OS X application that makes it really simple to get
PostgreSQL up and running, and also creates a postgres user that Phoenix uses as a default when
creating databases.
Any trouble with this step? Check out the PostgreSQL detailed installation guides31 or the Post-
greSQL section of Stack Overflow32 .
25
https://stackoverflow.com/questions/tagged/hex-pm
26
http://phoenixframework.org/
27
https://hexdocs.pm/phoenix/installation.html
28
https://stackoverflow.com/questions/tagged/phoenix-framework
29
https://www.postgresql.org/
30
https://postgresapp.com/
31
https://wiki.postgresql.org/wiki/Detailed_installation_guides
32
https://stackoverflow.com/questions/tagged/postgresql
33
https://github.com/asdf-vm/asdf