0% found this document useful (0 votes)
346 views

Elixir Elm Tutorial Sample

elm

Uploaded by

SumeetHearts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
346 views

Elixir Elm Tutorial Sample

elm

Uploaded by

SumeetHearts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Elixir and Elm Tutorial

Bijan Boustani
This book is for sale at http://leanpub.com/elixir-elm-tutorial

This version was published on 2017-09-16

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.

2017 Bijan Boustani


Tweet This Book!
Please help Bijan Boustani by spreading the word about this book on Twitter!
The suggested tweet for this book is:
Im learning functional web programming with Elixir and Elm!
https://leanpub.com/elixir-elm-tutorial
The suggested hashtag for this book is #ElixirElmTutorial.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
#ElixirElmTutorial
Contents

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.

What Were Building


The application well be building is a small game platform for the web. Well use Elixir and the
Phoenix web framework to power the back-end, where players can sign in and keep track of their
scores. Then, well use Elm on the front-end to create fun minigames. Well tie everything together
so we can pass data back and forth between the back-end and front-end. Users on our platform will
be able to join a chat to discuss the available minigames, and the scores from those games will be
updated on the platform in real-time. Well focus on building things with a strong foundation so we
can use these same concepts to create different web applications as well.

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.

Who Is This Book For?


This book is written for developers who already have some existing experience with web program-
ming. The goal is for the book to be a practical introduction to building a project with functional
web programming languages like Elixir and Elm.
We wont assume any prior experience with Elixir and Elm, and consider it more likely that youve
worked with languages like Ruby and JavaScript. But keep in mind that well occasionally forego
in-depth explanations and theory in an effort to gain insight into shipping a real project.
Well walk through initial explanations to give you just enough information about the fundamentals
and concepts so you can be productive. But there are other books that will provide more depth when
it comes to learning more about the languages themselves:
Introduction 2

Programming Elixir1 by Dave Thomas


An Introduction to Elm2 by Evan Czaplicki

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:

Some experience with HTML and CSS.


Familiarity with the command line and a text editor.
Preferably previous experience with Git and GitHub.
Preferably some experience working with a web framework.

Why Elixir and Elm?

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.

Elm is a compiled, functional language.


Elm is blazingly fast.
Elm programs are free from runtime errors. That means the language was designed in such a
way that makes a certain class of errors impossible, which provides us with an ability to make
guarantees about how our programs work.
The Elm compiler can be a helpful guide towards writing high quality code, and the error
messages provided are extremely helpful.
The elm-format tool helps with writing consistent code that is easier to read, write, and
maintain. While optional, this tool is highly recommended for Elm beginners because you
can configure it to automatically format code when you save a file in your editor.
With all the features Elm has to offer, the net result is confidence. As developers, we can be
more confident that our code is performing the way we intended, and that our programs will
function properly for our users.
Elm code is maintainable. Refactoring is a dream, and youll find yourself surprised at how
easy a significant refactor can feel after coming from other languages.

Elixir and Elm?


Elixir and Elm are young, functional programming languages that are optimized for your
happiness as a developer. They offer a programming experience that will make it fun to
develop applications, and over time those applications will be easy to extend and maintain.
The primary reason to pick up new languages like Elixir and Elm is that it will afford you with an
opportunity to acquire new ways of thinking. Many great lessons have been learned in the field of
programming over the past several decades, and unfortunately many developers are still working
in the dark on a daily basis. We ignore history at a great cost, and all too often make things difficult
on ourselves. Elixir and Elm are a chance at a fresh perspective.
7
http://elm-lang.org
Introduction 4

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:

Back-end: Elixir and Phoenix


Front-end: Elm, the Elm Architecture, and JavaScript
Version Control: Git and GitHub
Data: Ecto, PostgreSQL, and JSON
Deployment: Heroku

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.

Note on Phoenix Versions


In this book, were using the latest version of Phoenix available. Make sure youre working with
Phoenix 1.3, or the commands and files will all look different as you work through the instructions.
To fetch the latest version of Phoenix, run the following command:

1 $ mix archive.install https://github.com/phoenixframework/archives/raw/master/ph\


2 x_new.ez

Creating the Platform


The first step we need to take is to create the foundation for our application. To do that, lets open
up our Terminal and run the following command:

1 $ mix phx.new platform

It will ask the following question:

Fetch and install dependencies?

Enter the letter Y and the following output will be displayed:


Diving In 6

1 $ mix phx.new platform


2 * creating platform/config/config.exs
3 * creating platform/config/dev.exs
4 * creating platform/config/prod.exs
5 * creating platform/config/prod.secret.exs
6 * creating platform/config/test.exs
7 * creating platform/lib/platform/application.ex
8 * creating platform/lib/platform.ex
9 * creating platform/lib/platform_web/channels/user_socket.ex
10 * creating platform/lib/platform_web/views/error_helpers.ex
11 * creating platform/lib/platform_web/views/error_view.ex
12 * creating platform/lib/platform_web/endpoint.ex
13 * creating platform/lib/platform_web/router.ex
14 * creating platform/lib/platform_web.ex
15 * creating platform/mix.exs
16 * creating platform/README.md
17 * creating platform/test/support/channel_case.ex
18 * creating platform/test/support/conn_case.ex
19 * creating platform/test/test_helper.exs
20 * creating platform/test/platform_web/views/error_view_test.exs
21 * creating platform/lib/platform_web/gettext.ex
22 * creating platform/priv/gettext/en/LC_MESSAGES/errors.po
23 * creating platform/priv/gettext/errors.pot
24 * creating platform/lib/platform/repo.ex
25 * creating platform/priv/repo/seeds.exs
26 * creating platform/test/support/data_case.ex
27 * creating platform/lib/platform_web/controllers/page_controller.ex
28 * creating platform/lib/platform_web/templates/layout/app.html.eex
29 * creating platform/lib/platform_web/templates/page/index.html.eex
30 * creating platform/lib/platform_web/views/layout_view.ex
31 * creating platform/lib/platform_web/views/page_view.ex
32 * creating platform/test/platform_web/controllers/page_controller_test.exs
33 * creating platform/test/platform_web/views/layout_view_test.exs
34 * creating platform/test/platform_web/views/page_view_test.exs
35 * creating platform/.gitignore
36 * creating platform/assets/brunch-config.js
37 * creating platform/assets/css/app.css
38 * creating platform/assets/css/phoenix.css
39 * creating platform/assets/js/app.js
40 * creating platform/assets/js/socket.js
41 * creating platform/assets/package.json
42 * creating platform/assets/static/robots.txt
Diving In 7

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.

Configuring the Database


Now that weve created the files for our Phoenix application, lets change to that directory:

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.

Running the Server


Lets see what our new application looks like in the browser. To start the web server, run the following
command:

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

Phoenix Default Start Page

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 $

Our First Resource


Since we are building a small game platform, there are two primary resources that well want to get
started with:

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:

1 $ mix phx.gen.html Accounts Player players username:string score:integer

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

1 $ mix phx.gen.html Accounts Player players username:string score:integer


2 * creating lib/platform_web/controllers/player_controller.ex
3 * creating lib/platform_web/templates/player/edit.html.eex
4 * creating lib/platform_web/templates/player/form.html.eex
5 * creating lib/platform_web/templates/player/index.html.eex
6 * creating lib/platform_web/templates/player/new.html.eex
7 * creating lib/platform_web/templates/player/show.html.eex
8 * creating lib/platform_web/views/player_view.ex
9 * creating test/platform_web/controllers/player_controller_test.exs
10 * creating lib/platform/accounts/player.ex
11 * creating priv/repo/migrations/20170807120444_create_players.exs
12 * creating lib/platform/accounts/accounts.ex
13 * injecting lib/platform/accounts/accounts.ex
14 * creating test/platform/accounts/accounts_test.exs
15 * injecting test/platform/accounts/accounts_test.exs
16
17 Add the resource to your browser scope in lib/platform_web/router.ex:
18
19 resources "/players", PlayerController
20
21 Remember to update your repository by running migrations:
22
23 $ mix ecto.migrate

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:

1 scope "/", PlatformWeb do


2 pipe_through :browser # Use the default browser stack
3
4 get "/", PageController, :index
5 end

And were going to update it with our new players resource:

1 scope "/", Platform.Web do


2 pipe_through :browser # Use the default browser stack
3
4 get "/", PageController, :index
5 resources "/players", PlayerController
6 end

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

Now we can access http://0.0.0.0:4000/players11 and we should see the following:


11
http://0.0.0.0:4000/players
Diving In 14

Empty List of Players on Player Index Page

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

New Player Page

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

Player Show Page

Feel free to create some more player accounts so we have some data to work with on our players
page:
Diving In 17

Players Index with Sample Data

Updating our Home Page


We have a working players resource with an index of all the players, a show page to view a single
player, an edit page to update a single player, and the ability to delete players. But when we go back
to our home page at http://0.0.0.0:400013 , these pages arent accessible. Our users wouldnt know
that they need to visit the /players/new page to create their account. At some point, we will only
want our users to be able to create their accounts without being able to edit or delete others. To get
started, lets figure out where the HTML code is coming from for our home page.
Inside the lib/platform_web folder, there is a templates folder. This is where we put the HTML
code that we want to render in the browser. And instead of standard .html files, well see that the
files have a .html.eex extension. That means we can write standard HTML code, and we can also
embed Elixir code too.
Lets open the lib/platform_web/templates/page/index.html.eex file and take a look:

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:

1 <a class="btn btn-success" href="/players/new">Create Player Account</a>


2
3 <a class="btn btn-info" href="/players">List All Players</a>

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 :

Home Page with List Players Link

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.

Writing Elixir Code


Lastly, lets get some experience with writing Elixir code in our templates by converting our buttons
to use embedded Elixir code instead of simple HTML. The page will work the same way, but this
will give us a chance to use a Phoenix feature instead of writing HTML.
Phoenix gives us a link16 function we can use, and we can see a handful of examples provided in the
documentation.
15
http://0.0.0.0:4000
16
https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2
Diving In 20

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!":

1 <a class="btn btn-success" href="/players/new">Create Player Account</a>


2
3 <a class="btn btn-info" href="/players">List All Players</a>
4
5 <%= IO.inspect "Hello World!" %>

Lets take a look at the results in our browser:

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

1 <%= link("Create Player Account", to: "/players/new", class: "btn btn-success") \


2 %>
3
4 <%= link("List All Players", to: "/players", class: "btn btn-info") %>

We can now verify that our links still work the same way they did previously:

Link to Players Page Using Embedded Elixir

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

Ecto relationships, migrations, and schemas.


Adding JSON API features for players.
Elm Introduction
Brief introduction to the Elm language and tooling.
Covers modules, functions, types, formatting, and refactoring.
Elm Setup
Introduction to Brunch and Phoenix assets.
Configuring Phoenix to work with Elm.
Elm Application
Starting our Elm front-end application.
Importing and using Elm packages.
Working with familiar HTML as a bridge to learning Elm.
Breaking up code into small, pure functions.
Working with the concept of Maybe in Elm.
Iterating through lists of data.
Elm Architecture
Structure of the Elm Architecture.
Working with the Record data type in Elm.
Adding the Model, Update, Subscriptions, and View.
Pulling the application together with the Main function.
Adding initial interactivity with Html.Events.
Elm API Data (Incomplete)
Reading JSON API data from Phoenix.
Decoding JSON and working with game data in Elm.
Our First Game
Creating a space within Phoenix for an Elm game.
Working with SVG to create a small game canvas.
Adding a small game character and item.
Refactoring Elm code with let expressions and small functions.
Adding Interaction
Working with Elm subscriptions and keyboard input.
Adjusting character position.
Spawning and collecting items.
Working with randomness.
Displaying Game Data
Rendering text in the game window.
Displaying the player score, items collected, and time remaining.
Working with time.
Handling Game States
Introducing union types for game states.
Rendering different elements depending on current game states.
Creating start, success, and game over states.
Current Outline 24

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:

1 $ brew install elixir

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:

1 $ mix archive.install https://github.com/phoenixframework/archives/raw/master/ph\


2 x_new.ez

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 .

Working with Versions


The steps above should be all thats required to get started. If youre interested in working with
multiple versions different languages, check out the asdf version manager33 .

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

You might also like