Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Notes on learning Elixir and Phoenix

Notes on learning Elixir and Phoenix

Just some assorted notes I've made while digging into Phoenix, Elixir and friends. I'm coming from a strong Rails background, so many of these will refer to features from that framework.

Views / Templates

Biggest difference from Rails?

Unlike Rails, where rendering is almost always performed by a template file, the responsibility of rendering a response in Phoenix lies with a view module (that typically corresponds to the current controller module.) This view module will typically offer a whole bunch of render functions (matching different parameters, first and foremost the template name.) Templates (found in web/templates/) will directly compile into such functions.

Is there something like Slim for Phoenix?

Yup: Slime and phoenix_slime. There's also phoenix_haml if you prefer that syntax.

Can I use Turbolinks?

Yup, Turbolinks 5 is easy enough to integrate into non-Rails apps. This blog post has details.


How do I validate for uniqueness?

  1. In a migration, add a unique index to your database:

    create unique_index(:users, [:email])
  2. Teach your Changeset to handle index violation errors reported by the database:

    cast(user, params, ~w(email), ~w())
    |> unique_constraint(:email)

Is there a seed script?

Yup: priv/repo/seeds.exs. It's a plain Elixir Script that you can run through mix run priv/repo/seeds.exs.


Where's my Asset Pipeline?

Phoenix uses Brunch for assets, one of the many asset handlers from the domain of Node.js/Javascript. Core configuration is in your project's brunch-config.js file.

Phoenix is configured to automatically recompile assets when they change. If you want to use another build tool than Brunch, apparently this is possible, but you need to set up automatic recompilation yourself.

What about CSS concatenation order?

By default, Brunch will concatenate CSS files found in web/static/css in alphabetical order, but it will always use the default app.css last. (You can change this in brunch-config.js.)

How do I add Sass to my project?

Assuming you're using the default Brunch setup, just add the sass-brunch npm package through NPM or Yarn. You'll probably want to rename your app.css to app.scss (to enable Sass syntax) and change the related entry in brunch-config.js (to make sure the file is inserted last.)


What does a typical controller test look like?

defmodule MyApp.PageControllerTest do
  use MyApp.ConnCase

  test "GET /", %{conn: conn} do
    conn = get conn, "/"
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.