elixir and elm tutorial - leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning...

29

Upload: others

Post on 20-May-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these
Page 2: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Elixir and Elm Tutorial

Bijan Boustani

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

This version was published on 2019-01-06

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

© 2017 - 2019 Bijan Boustani

Page 3: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1What We’re Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Who Is This Book For? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Why Elixir and Elm? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Technology Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Diving In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Creating the Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Configuring the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Running the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Our First Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Running a Migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Creating Players . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Updating our Home Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Writing Elixir Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Appendix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Quick Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Working with Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Recommended Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Page 4: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

IntroductionWelcome to the world of functional web programming! In this book, we’ll learn how to create fun,scalable, and maintainable web applications. We’ll be using a wide range of web technologiesalong with the latest ideas from emerging languages like Elixir and Elm to craft a fun experience.Rather than focusing on theory, we’ll take a practical approach and build a real-world application.

What We’re Building

The application we’ll be building together is a small game platform for the web. We’ll useElixir and the Phoenix web framework to power the back-end, where players can sign in and keeptrack of their scores. Then, we’ll use Elm on the front-end to create fun minigames. We’ll connecteverything together so we can pass data back and forth between the back-end and front-end. Userson our platform will view available minigames, and the scores from those games will be updatedon the platform in real-time. We’ll focus on building things with a solid foundation so we can usethese same concepts to create different web applications as well.

Acknowledgements

I would like to thank Envy Labs and Code School for fostering environments where I was able towork hard and learn and grow. I’d also like to thank José Valim and Evan Czaplicki for craftingsuch beautiful and fun programming languages. And thanks to Bret Victor for inspiring all of uswith 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 functionalweb programming languages like Elixir and Elm.

We won’t assume any prior experience with Elixir and Elm, and consider it more likely that you’veworked with languages like Ruby and JavaScript. But keep in mind that we’ll occasionally foregoin-depth explanations and theory in an effort to gain insight into shipping a real project.

We’ll walk through initial explanations to give you just enough information about the fundamentalsand concepts so you can be productive. But there are other books that will provide more depth whenit comes to learning more about the languages themselves:

Page 5: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Introduction 2

• Programming Elixir¹ by Dave Thomas• An Introduction to Elm² by Evan Czaplicki

The material in this book is intended to be crafted in such a way that you can follow along simplyby typing in the relevant code examples. Beginners can still learn a lot simply by following alongand building the application, because sometimes in programming you need to be exposed to certainconcepts and ideas before they become easy to understand. The experience of building somethingwill be fun and engaging; and a deeper understanding will follow with increased familiarity andexperience.

Prerequisites

In addition to the notes above about the intended audience for this book, here are some additionalprerequisites 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

Elixir³ 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 ofstability and scalability.

• Concurrency is at the heart of Elixir. Instead of getting faster processors, computers these daysare getting processors with more cores. That means we need to write our programs in such away that allows them to be distributed across multiple cores so our programs can outperformour competitors. As an example, compare the latest 13-inch Macbook Pro models⁴ with 2-coreprocessors with 15-inch Macbook Pro models⁵ with 6-core processors. Then, see how manycores (or “virtual CPUs”) you’ll have access to when you deploy your application to a multi-core web server⁶.

¹https://pragprog.com/book/elixir16/programming-elixir-1-6²https://guide.elm-lang.org³http://elixir-lang.org⁴http://www.apple.com/shop/buy-mac/macbook-pro/13-inch⁵http://www.apple.com/shop/buy-mac/macbook-pro/15-inch⁶https://www.digitalocean.com/pricing/#droplet

Page 6: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Introduction 3

• The Phoenix web framework provides us with the ability to create new projects quickly. Forweb developers that have worked with Ruby on Rails, the concepts will be familiar and easyto pick up.

• Elixir also inherits amazing features from other languages:– Ruby’s readable syntax and philosophy of developer happiness.– Erlang’s stability and scalability.– F#’s magical pipe operator for data transformation.– LISP’s macros and metaprogramming.

Elm

Elm⁷ is an exciting new functional language that is still evolving. It’s 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 away that makes a certain class of errors impossible, which provides us with an ability to makeguarantees about how our programs work.

• The Elm compiler can be a helpful guide towards writing high quality code, and the errormessages provided are extremely helpful.

• The elm-format tool helps with writing consistent code that is easier to read, write, andmaintain. While optional, this tool is highly recommended for Elm beginners because youcan 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 bemore confident that our code is performing the way we intended, and that our programs willfunction properly for our users.

• Elm code is maintainable. Refactoring is a dream, and you’ll find yourself surprised at howeasy 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 yourhappiness as a developer. They offer a programming experience that will make it fun todevelop 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 anopportunity to acquire new ways of thinking. Many great lessons have been learned in the field ofprogramming over the past several decades, and unfortunately many developers are still workingin the dark on a daily basis. We ignore history at a great cost, and all too often make things difficulton ourselves. Elixir and Elm are a chance at a fresh perspective.

⁷http://elm-lang.org

Page 7: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Introduction 4

Technology Stack

There are many technologies involved in building and deploying modern web applications. We’llbe using a straightforward stack of technologies that will allow us the flexibility to scale ourapplications gracefully. Here’s the short version of the technology stack:

• Back-end: Elixir• Front-end: Elm

These technologies stand on the shoulders of giants, so here’s a little more information about othertechnologies we’ll 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 you’re coming from a background in working with Ruby on Rails or JavaScript web frameworks,then you’ll have a head start in being able to grasp the content andmove smoothly through the book.Something to keep in mind is that Elixir and Elm are functional languages. If you’re coming froman object-oriented background, you may find some of the concepts unfamiliar at first, but the initialdiscomfort will pay off over time as you learn to solve problems in an elegant functional manner.

Summary

In this introduction, we touched briefly on the application we’ll be building and some of thereasoning for choosing Elixir and Elm as languages. But the fun part is creating with thesetechnologies and experiencing the benefits first-hand, so let’s dive in and start building ourapplication in the next chapter.

Page 8: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving InInstead of simply reading about Elixir and Elm, let’s dive in and experience what these languageshave to offer. In this chapter, we’re going to avoid detailed explanations and theory in favor ofquickly building the foundation for our project. We’ll focus on running the necessary commands inthe Terminal and writing the code we’ll need to start creating our application.

Later in the book, we’ll cover more about the fundamentals of Elixir, but for now let’s focus onfollowing along and getting a glimpse of how to get an application up and running.

Installation

If you haven’t already set up your development environment with Elixir, Phoenix, and PostgreSQL,check out the Appendix in the back of the book for quick installation instructions.

Also note that we’re working with the latest version of Phoenix in this book. Make sure you havePhoenix 1.4 installed, or the commands and files will all look different as you work through thematerial.

Creating the Platform

The first step we need to take is to create the foundation for our application. To do that, let’s openup 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 (note that some of the file creation lineswere trimmed for the sake of readability):

Page 9: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 6

1 $ mix phx.new platform

2 * creating platform/mix.exs

3 * creating platform/README.md

4 * creating platform/assets/...

5 * creating platform/config/...

6 * creating platform/lib/platform/...

7 * creating platform/lib/platform_web/...

8 * creating platform/priv/...

9 * creating platform/test/...

10

11 Fetch and install dependencies? [Yn] Y

12 * running mix deps.get

13 * running mix deps.compile

14 * running cd assets && npm install && node node_modules/webpack/bin/webpack.js --mod\

15 e development

16

17 We are all set! Go into your application by running:

18

19 $ cd platform

20

21 Then configure your database in config/dev.exs and run:

22

23 $ mix ecto.create

24

25 Start your Phoenix app with:

26

27 $ mix phx.server

28

29 You can also run your app inside IEx (Interactive Elixir) as:

30

31 $ iex -S mix phx.server

Phoenix displays a lot of helpful information. First, the output shows all the files that were generated(don’t worry if it seems overwhelming at first; we’re 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 we’ve created the files for our Phoenix application, let’s change to that directory:

Page 10: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 7

1 $ cd platform

We can set up the database for our project by running the following command:

1 $ mix ecto.create

If you run into issues here, it likely means you’ll have to configure your PostgreSQL installation oradjust the database username and password fields at the bottom of the config/dev.exs file. You canalso check out the Appendix at the back of this book for more information on PostgreSQL.

Since this is the first time we’re running a command with our new application, we’ll see that it takestime for the source code to compile. Elixir runs on the Erlang virtual machine, and needs to compilethe source to bytecode before we can run our programs. It takes time to run initially, but subsequentcommands will run noticeably faster after this.

If the database creation was successful, we’ll 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

Let’s seewhat our new application looks like in the browser. To start theweb server, run the followingcommand:

1 $ mix phx.server

This will start a server and allow us to visit http://localhost:4000⁸ in a browser to see our newapplication running. Here is what the output will look like (ignoring the additional output fromWebpack):

1 $ mix phx.server

2 [info] Running PlatformWeb.Endpoint with cowboy using http://localhost:4000

⁸http://localhost:4000

Page 11: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 8

Phoenix Default Start Page

At this point, you might be impressed that we managed to get a full back-end up and running soquickly. Or, youmay have seen similar features in other frameworks, and perhaps you’re nonplussedwith our progress so far. We’re going to start adding features to our application, but it’s worth takinga moment to appreciate 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, let’s stop the Phoenix web server. Go back to the Terminal where the serveris running, and press Control + C on your keyboard twice to stop the server. This tends to be thesimplest way to exit a running Elixir program, and here is what the output will look like as you stopthe running web server:

Page 12: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 9

1 $ mix phx.server

2 [info] Running Platform.Endpoint with cowboy using http://localhost: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 we’ll want to getstarted with:

• Players• Games

We’re going to start by using something called a generator to keep moving quickly. It’s going tocreate a lot of the files we need to work with. Then, we’ll cover more about how it all works later.

Let’s 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, we’re creating players for our game platform. We want to be able to useour browser to interact with the data, so we’re starting with phx.gen.html⁹ to generate an HTMLresource.

Because we’re creating player accounts for our application, we use Accounts to provide a contextfor our resource. Then, we use Player for the module name and players to indicate the pluralizedform, 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). We’ll 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.

You’ll see that the generator creates quite a few files for us, and once again Phoenix gives us somehelpful tips about what to do next:

⁹https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Html.html

Page 13: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 10

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

Don’t worry too much about all those files yet, but the information at the bottom is important. Inorder to configure our application to work with our new player accounts, we’ll need to add them tothe 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. Let’s go ahead and followalong. Open the lib/platform_web/router.ex file and see what it looks like:

Page 14: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 11

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

10 end

11

12 pipeline :api do

13 plug :accepts, ["json"]

14 end

15

16 scope "/", PlatformWeb do

17 pipe_through :browser

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 (whichwe’re going to use now), and the other one is for JSON (which we’ll also use later). And we can evensee that the scope is already set up for us to access the HTML with our browser. That’s how wewere able to load the http://localhost:4000 URL and see the initial starter page. Don’t worry ifit seems confusing at first. All you need to know is that this block of code is where we’ll focus fornow:

1 scope "/", PlatformWeb do

2 pipe_through :browser

3

4 get "/", PageController, :index

5 end

And we’re going to update it with our new players resource:

Page 15: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 12

1 scope "/", PlatformWeb 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://localhost:4000/players¹⁰, we’ll soon be able to start creatingthe players for our game platform.

Running a Migration

Our application has all the information it needs to render the players resource that we created, butwe still need to tell the database about the changes we made. For the database to store our playerdata (with the username and score fields), we’ll 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 weshould 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 forw\

5 ard

6 08:18:44.182 [info] create table players

7 08:18:44.371 [info] == Migrated in 0.1s

Creating Players

Let’s start our server again and see our new player resource in action:

1 $ mix phx.server

¹⁰http://localhost:4000/players

Page 16: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 13

Now we can access http://localhost:4000/players¹¹ and we should see the following:

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 NewPlayer link at the bottom and try creating a player on the http://localhost:4000/players/new¹²page.

¹¹http://localhost:4000/players¹²http://localhost:4000/players/new

Page 17: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 14

New Player Page

After we successfully create a new player account, we’ll see the “show” page with the individualplayer’s data (notice the player id number is displayed in the URL too):

Page 18: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 15

Player Show Page

Feel free to create additional player accounts so we have data to work with on our players page:

Players Index with Sample Data

Page 19: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 16

Updating our Home Page

We have a working players resource with an index of all the players, a show page to view a singleplayer, an edit page to update a single player, and the ability to delete players. But when we go backto our home page at http://localhost:4000¹³, these pages aren’t accessible. Our users wouldn’tknow that they need to visit the /players/new page to create their account. At some point, we willonly want our users to be able to create their accounts without being able to edit or delete others.To get started, let’s 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 HTMLcode that we want to render in the browser. And instead of standard .html files, we’ll see that thefiles have a .html.eex extension. That means we can write standard HTML code, and we can alsoembed Elixir code too.

Let’s open the lib/platform_web/templates/page/index.html.eex file and take a look (note thatsome of the HTML was trimmed for the sake of readability):

1 <section class="phx-hero">

2 <h1><%= gettext "Welcome to %{name}!", name: "Phoenix" %></h1>

3 <p>A productive web framework that<br/>does not compromise speed and maintainabili\

4 ty.</p>

5 </section>

6

7 <section class="row">

8 <article class="column">

9 <h2>Resources</h2>

10 <!-- ... -->

11 </article>

12 <article class="column">

13 <h2>Help</h2>

14 <!-- ... -->

15 </article>

16 </section>

This should look familiar in that it’s mostly comprised of standard HTML code. It’s the HTML thatwe’re seeing when we load http://localhost:4000¹⁴. Let’s delete this code and create a coupleof simple links to our player pages. First, remove all the existing code in the lib/platform_-

web/templates/page/index.html.eex file. Then, replace it with the following:

¹³http://localhost:4000¹⁴http://localhost:4000

Page 20: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 17

1 <div class="container">

2 <a class="button" href="/players/new">Create Player Account</a>

3 <a class="button" href="/players">List All Players</a>

4 </div>

Save the file and go back to the browser to see the changes (make sure the Phoenix web server isstill running or restart the server with mix phx.server) at http://localhost:4000¹⁵:

Home Page with List Players Link

Phoenix comes with a Live Reload feature that automatically refreshes our application in thebrowser. If the Phoenix server was still running, then the home page was automatically regeneratedand should now display the buttons that we created. Try them out, and they should enable users tosuccessfully navigate to the player pages in our application.

Writing Elixir Code

Lastly, let’s get some experience with writing Elixir code in our templates by converting our buttonsto use embedded Elixir code instead of simple HTML. The page will work the same way, but thiswill give us a chance to use a Phoenix feature instead of writing HTML.

Phoenix gives us a link¹⁶ function we can use, and we can see a handful of examples provided in thedocumentation.

Since we’re working with a .eex file, that means we can embed Elixir code by surrounding it withtags like this: <%= ... %>. The Elixir code that we put inside those tags will be evaluated, and thenrendered onto the page.

¹⁵http://localhost:4000¹⁶https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2

Page 21: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 18

A helpful debugging technique while working with Elixir is to use the IO.inspect¹⁷ function todisplay results. In this example, we’re using the IO module with the inspect function, and we’repassing it the string "Hello World!":

1 <div class="container">

2 <a class="button" href="/players/new">Create Player Account</a>

3 <a class="button" href="/players">List All Players</a>

4

5 <%= IO.inspect("Hello World!") %>

6 </div>

Let’s take a look at the results in our browser:

Embedded Elixir

We can do something similar to embed a link on our page. We won’t need to explicitly mention themodule (Phoenix.HTML.Link), because we already have access to some helpful Phoenix functionsin this context. We can recreate our existing HTML links with the following code by passing thelink text, the location, and a button class to make it look nice (Phoenix comes with a small CSSframework preinstalled):

1 <div class="container">

2 <%= link("Create Player Account", to: "/players/new", class: "button") %>

3 <%= link("List All Players", to: "/players", class: "button") %>

4 </div>

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

¹⁷https://hexdocs.pm/elixir/IO.html#inspect/2

Page 22: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Diving In 19

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 foundationfor our application with a Phoenix back-end. We leveraged the Phoenix generators to create ourplayers resource, started getting an idea of what the Phoenix folder structure looks like, and beganediting files. We also learned a little about routing and working with the database.

We’ve gotten an introductory look at how to create a full Elixir and Phoenix web platform, and weeven created a couple of player records that we can use as we continue building. But we movedquickly through these steps, and we don’t have a solid understanding of how all these pieces fittogether yet. In the next chapter, we’ll delve into some Elixir basics. And instead of using generatorslike we did in this chapter, we’ll manually create features in our application so we can continueincreasing our experience.

Page 23: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

OutlineThe table of contents at the beginning of this book is available as a cursory overview of all thechapters and sections in the book. The outline below is an attempt to break down the topics andconcepts covered within each chapter.

• 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 sign in and session features.

• Phoenix API– Generating a JSON API for games.

Page 24: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Outline 21

– Routing and scopes.– 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– Reading JSON API data from Phoenix.– Decoding JSON and working with game data in Elm.

• Design and Usability– Viewing application routes.– Working with CSS and working with Bootstrap classes.– Authorizing actions for player account features.– Styling for the lists of players and games.

• Game Setup– Creating a new Elm file for our first game.– Configuring Phoenix to compile multiple Elm applications.– Adding a slug field for working with games.

• Our First 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

Page 25: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Outline 22

– 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.

• Phoenix Channels and Elm Ports– Getting started with Phoenix channels.– Creating and joining a channel.– Introduction to Elm ports and connecting Elm to Phoenix.– Sending data over the socket.

• Syncing Score Data– Sending and receiving data over the socket.– Displaying the results on the game page.– Working at the intersection of Phoenix, JavaScript, and Elm.

• Socket Authentication– Working with Phoenix user tokens for socket authentication.– Enabling multiple players to track changes over the socket.– Extending gameplays with additional data.– Refactoring channels with pattern matching.

• Saving Score Data– Using the channel to save scores to the database.– Working with Elm flags to send data from JavaScript to Elm.– Differentiating between authenticated and anonymous players.

• Finishing Touches– Fetching saved gameplays from the database to display for our game.– Fetching the list of players from the database.– Creating helper functions to associate players and gameplays.– Displaying player names and scores for gameplays.

• What’s Next?– Additional features and ideas that didn’t make it into the book.– Planning for possible future versions of this book.

• Appendix– Quick installation instructions.– Tooling recommendations.

• Contact– Congrats and contact information.– Request for feedback and ideas for the future.

Page 26: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

AppendixQuick Install

This book is intended for developers with some previous experience, so installing these languagesand tools shouldn’t be overly difficult or time-consuming. Having said that, it’s easy to get trippedupwith installation and configuration steps, so feel free to create a GitHub issue¹⁸ if you think there’san easier approach to setting things up.

The intention for this chapter is to get everything we’ll need installed quickly so we can start creatingPhoenix projects.

These instructions assume that you’re running macOS, but instructions can also be found online forinstalling these tools on Linux.

Elixir

First, let’s install Elixir¹⁹ with Homebrew²⁰. This command will also install the latest version ofErlang²¹ 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.7.0

Any trouble with this step? Check out the Elixir install page²² or the Elixir section of StackOverflow²³.

Hex

Hex²⁴ is the package manager for the Elixir and Erlang ecosystems. Once you have Elixir installed,it’s easy to install Hex with the following command:

¹⁸https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues¹⁹https://elixir-lang.org²⁰https://brew.sh²¹https://www.erlang.org²²https://elixir-lang.org/install.html²³https://stackoverflow.com/questions/tagged/elixir²⁴https://hex.pm

Page 27: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Appendix 24

1 $ mix local.hex

Any trouble with this step? Check out the Hex section of Stack Overflow²⁵.

Phoenix

Phoenix²⁶ is a web application framework built with the Elixir language. You can install the latestversion with the following command:

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

2 w.ez

You can verify that Phoenix has been installed properly by running the mix help command, andyou 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 docs²⁷ or the Phoenix section of StackOverflow²⁸.

PostgreSQL

We’ll be using PostgreSQL²⁹ for our database. The easiest way to get started if you’re new toPostgreSQL is to use Postgres.app³⁰. It’s a macOS application that makes it really simple to getPostgreSQL up and running, and also creates a postgres user that Phoenix uses as a default whencreating databases.

Any trouble with this step? Check out the PostgreSQL detailed installation guides³¹ or the Post-greSQL section of Stack Overflow³².

Working with Versions

The steps above should be all that’s required to get started. If you’re interested in working withmultiple versions different languages, check out the asdf version manager³³.

²⁵https://stackoverflow.com/questions/tagged/hex-pm²⁶http://phoenixframework.org²⁷https://hexdocs.pm/phoenix/installation.html²⁸https://stackoverflow.com/questions/tagged/phoenix-framework²⁹https://www.postgresql.org³⁰https://postgresapp.com³¹https://wiki.postgresql.org/wiki/Detailed_installation_guides³²https://stackoverflow.com/questions/tagged/postgresql³³https://github.com/asdf-vm/asdf

Page 28: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Appendix 25

Recommended Tools

Throughout this book, we opt for a simple approach to afford ourselves an opportunity to learnabout Elixir, Phoenix, and Elm as we put together a demo application. As you start to develop moreinvolved projects, it’s a good idea to review additional tools and services that can make your lifeeasier.

The hex.pm³⁴ package manager is an invaluable tool for finding useful libraries for your projects. Forexample, if you want to allow your users to write Markdown syntax, you can look up “Markdown”on hex.pm and find that the Earmark³⁵ package works really well for this.

Listed below are additional tools for your consideration.

Authentication

Want to build more robust authentication features for your application? Consider checking out thefollowing options:

• ueberauth³⁶• guardian³⁷

Authorization

We briefly touched on authorizing actions in our demo application. If you need to work withadditional authorization policies, take the following into consideration:

• BodyGuard³⁸

Code Quality

Credo is a code quality tool that performs static analysis on your Elixir code and provides helpfultips and feedback. It’s really helpful as a way to learn solid Elixir conventions and keep the codethroughout your project consistent.

• Credo³⁹³⁴https://hex.pm³⁵https://github.com/pragdave/earmark³⁶https://github.com/ueberauth/ueberauth³⁷https://github.com/ueberauth/guardian³⁸https://github.com/schrockwell/bodyguard³⁹https://github.com/rrrene/credo

Page 29: Elixir and Elm Tutorial - Leanpubsamples.leanpub.com/elixir-elm-tutorial-sample.pdf · reasoning for choosing Elixir and Elm as languages. But the fun part is creating with these

Appendix 26

Documentation

Elixir has amazing documentation tools, which explains why the docs are so fantastic. Check out theElixir guide on writing documentation⁴⁰ and consider using ExDoc to generate docs for your project.

• ExDoc⁴¹

Continuous Integration

Early versions of this book included material on Continuous Integration and Continuous Delivery.Although it ended up being outside the scope of our content, it’s essential to have a CI server toautomatically run your tests. Check out the following options, and consider hooking them into yourGitHub repository to automatically deploy your application.

• CircleCI⁴²• Semaphore⁴³

Monitoring

Once your project is deployed to production, it’s a good idea to monitor the performance and watchfor errors. AppSignal is a good option for tracking this data and keeping your application runningsmoothly.

• AppSignal⁴⁴

Testing

Because we used the Phoenix generators to scaffold out our initial features, our demo applicationcame with quite a few tests. So we have examples of how to work with ExUnit in our project, butWallaby is a great option for writing highly readable integration tests concurrently.

• Wallaby⁴⁵

⁴⁰https://hexdocs.pm/elixir/writing-documentation.html⁴¹https://github.com/elixir-lang/ex_doc⁴²https://circleci.com⁴³https://semaphoreci.com⁴⁴https://appsignal.com/elixir⁴⁵https://github.com/keathley/wallaby