<<

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 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 - 2019 Bijan Boustani Contents

Introduction ...... 1 What We’re 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 Installation ...... 5 Creating the Platform ...... 5 Configuring the Database ...... 6 Running the Server ...... 7 Our First Resource ...... 9 Routing ...... 10 Running a Migration ...... 12 Creating Players ...... 12 Updating our Home Page ...... 16 Writing Elixir Code ...... 17 Summary ...... 19

Outline ...... 20

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

Welcome 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 technologies along 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 use Elixir and the Phoenix web framework to power the back-end, where players can sign in and keep track of their scores. Then, we’ll use Elm on the front-end to create fun minigames. We’ll connect everything together so we can pass data back and forth between the back-end and front-end. Users on our platform will view available minigames, and the scores from those games will be updated on the platform in real-time. We’ll focus on building things with a solid 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 environments where I was able to work hard and learn and grow. I’d also like to thank José Valim and Evan Czaplicki for crafting such beautiful and fun programming languages. And thanks to 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 won’t assume any prior experience with Elixir and Elm, and consider it more likely that you’ve worked with languages like Ruby and JavaScript. But keep in mind that we’ll occasionally forego in-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 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 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 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

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 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 models⁴ with 2-core processors with 15-inch Macbook Pro models⁵ with 6-core processors. Then, see how many cores (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 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: – 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 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 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 you’ll 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.

⁷http://elm-lang.org Introduction 4

Technology Stack

There are many technologies involved in building and deploying modern web applications. We’ll be using a straightforward stack of technologies that will allow us the flexibility to scale our applications 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 other technologies 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 and move smoothly through the book. Something to keep in mind is that Elixir and Elm are functional languages. If you’re coming from an object-oriented background, you may find some of the concepts unfamiliar at first, but the initial discomfort 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 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 let’s dive in and start building our application in the next chapter. Diving In

Instead of simply reading about Elixir and Elm, let’s dive in and experience what these languages have to offer. In this chapter, we’re going to avoid detailed explanations and theory in favor of quickly building the foundation for our project. We’ll focus on running the necessary commands in the 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 on following 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 have Phoenix 1.4 installed, or the commands and files will all look different as you work through the material.

Creating the Platform

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

1 $ mixphx.newplatform

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 lines were trimmed for the sake of readability): 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: 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 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 we’re running a command with our new application, we’ll see that it takes time for the to compile. Elixir runs on the Erlang virtual machine, and needs to compile the source to bytecode before we can run our programs. It takes time to run initially, but subsequent commands 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 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://localhost:4000⁸ in a browser to see our new application running. Here is what the output will look like (ignoring the additional output from Webpack):

1 $ mix phx.server 2 [info] Running PlatformWeb.Endpoint with cowboy using http://localhost:4000

⁸http://localhost:4000 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 so quickly. Or, you may have seen similar features in other frameworks, and perhaps you’re nonplussed with our progress so far. We’re going to start adding features to our application, but it’s worth taking a 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 server is running, and press Control + C on your keyboard twice to stop the server. This tends to be the simplest way to exit a running Elixir program, and here is what the output will look like as you stop the running web server: 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 get started with:

• Players • Games

We’re going to start by using something called a generator to keep moving quickly. It’s going to create 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 use our browser to interact with the data, so we’re starting with phx.gen.html⁹ to generate an HTML resource. Because we’re 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). 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 some helpful tips about what to do next: ⁹https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Html.html 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. In order to configure our application to work with our new player accounts, we’ll 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. Let’s go ahead and follow along. Open the lib/platform_web/router.ex file and see what it looks like: 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 # Otherscopesmayusecustomstacks. 23 # scope"/api",PlatformWebdo 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 we’re going to use now), and the other one is for JSON (which we’ll also use later). And we can even see that the scope is already set up for us to access the HTML with our browser. That’s how we were able to load the http://localhost:4000 URL and see the initial starter page. Don’t worry if it seems confusing at first. All you need to know is that this block of code is where we’ll focus for now:

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: 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 creating the players for our game platform.

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 we made. For the database to store our player data (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 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 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 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 New Player 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 Diving In 14

New Player Page

After we successfully create a new player account, we’ll see the “show” page with the individual player’s data (notice the player id number is displayed in the URL too): 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 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 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://localhost:4000¹³, these pages aren’t accessible. Our users wouldn’t 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, 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 HTML code that we want to render in the browser. And instead of standard .html files, we’ll 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. Let’s open the lib/platform_web/templates/page/index.html.eex file and take a look (note that some of the HTML was trimmed for the sake of readability):

1

2

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

3

A productive web framework that
does not compromise speed and maintainabili\ 4 ty.

5
6 7
8
9

Resources

10 11
12
13

Help

14 15
16

This should look familiar in that it’s mostly comprised of standard HTML code. It’s the HTML that we’re seeing when we load http://localhost:4000¹⁴. Let’s delete this code and create a couple of 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 Diving In 17

1

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://localhost:4000¹⁵:

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, let’s 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 link¹⁶ function we can use, and we can see a handful of examples provided in the documentation. Since we’re 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.

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

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

1

2 Create Player Account 3 List All Players 4 5 <%= IO.inspect("Hello World!") %> 6

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 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 a button class to make it look nice (Phoenix comes with a small CSS framework preinstalled):

1

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

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

¹⁷https://hexdocs.pm/elixir/IO.html#inspect/2 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 foundation for our application with a Phoenix back-end. We leveraged the Phoenix generators to create our players resource, started getting an idea of what the Phoenix folder structure looks like, and began editing 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 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 don’t have a solid understanding of how all these pieces fit together yet. In the next chapter, we’ll delve into some Elixir basics. And instead of using generators like we did in this chapter, we’ll manually create features in our application so we can continue increasing our experience. Outline

The table of contents at the beginning of this book is available as a cursory overview of all the chapters and sections in the book. The outline below is an attempt to break down the topics and concepts 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. 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 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. Appendix

Quick Install

This book is intended for developers with some previous experience, so installing these languages and tools shouldn’t be overly difficult or time-consuming. Having said that, it’s easy to get tripped up with installation and configuration steps, so feel free to create a GitHub issue¹⁸ if you think there’s an easier approach to setting things up. The intention for this chapter is to get everything we’ll need installed quickly so we can start creating Phoenix projects. These instructions assume that you’re running macOS, but instructions can also be found online for installing these tools on Linux.

Elixir

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

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 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 latest version 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, 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 docs²⁷ or the Phoenix section of Stack Overflow²⁸.

PostgreSQL

We’ll be using PostgreSQL²⁹ for our database. The easiest way to get started if you’re new to PostgreSQL is to use Postgres.app³⁰. It’s a macOS 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 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 with multiple 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 Appendix 25

Recommended Tools

Throughout this book, we opt for a simple approach to afford ourselves an opportunity to learn about Elixir, Phoenix, and Elm as we put together a demo application. As you start to develop more involved projects, it’s a good idea to review additional tools and services that can make your life easier. The hex.pm³⁴ package manager is an invaluable tool for finding useful libraries for your projects. For example, 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 the following options:

• ueberauth³⁶ • guardian³⁷

Authorization

We briefly touched on authorizing actions in our demo application. If you need to work with additional 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 helpful tips and feedback. It’s really helpful as a way to learn solid Elixir conventions and keep the code throughout 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 Appendix 26

Documentation

Elixir has amazing documentation tools, which explains why the docs are so fantastic. Check out the Elixir 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 to automatically run your tests. Check out the following options, and consider hooking them into your GitHub 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 watch for errors. AppSignal is a good option for tracking this data and keeping your application running smoothly.

• AppSignal⁴⁴

Testing

Because we used the Phoenix generators to scaffold out our initial features, our demo application came with quite a few tests. So we have examples of how to work with ExUnit in our project, but Wallaby 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