Today I Learned

A Hashrocket project

91 posts about #elixir

Create A List Of Atoms

The ~w sigil makes it easy to create a word list -- a list of strings -- where each word is separated by a space.

> ~w(bulbasaur charmander squirtle)
["bulbasaur", "charmander", "squirtle"]

By appending an a onto that sigil construct, you are instructing Elixir that you would instead like a list of atoms.

> ~w(bulbasaur charmander squirtle)a
[:bulbasaur, :charmander, :squirtle]


Serve static files/directories in Phoenix

Phoenix will by default server some files and directories from priv/static. More specifically css/, fonts/, images/, js/, favicon.ico and robots.txt. If you need to add a new directory however simply creating it in priv/static will not make Phoenix serve it. You need to explicitly add it.

Say your project is called ChicagoElixir you will need to go to your endpoint configuration, typically in: lib/chicago_elixir/web/endpoint.ex. There you will find the following configuration:

  plug Plug.Static,
    at: "/", from: :chicago_elixir, gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)

Simply add the new folder or file name to the list in only and restart your Phoenix server.

Inspecting The Process Message Queue

A core tenant of Elixir is message passing between processes. So, if a process is sent a message, where does that message go? What happens if it gets sent many messages? The function allows us to inspect the message queue.

First, let's send some messages (to ourself) and then keep an eye on the length of the message queue as we go.

> send self(), {:error, "this is bad"}
{:error, "this is bad"}
>, :message_queue_len)
{:message_queue_len, 1}
> send self(), {:hello, "world"}
{:hello, "world"}
>, :message_queue_len)
{:message_queue_len, 2}

Now, I am curious what those specific messages are. Let's ask for the messages that are in the message queue.

>, :messages)
{:messages, [error: "this is bad", hello: "world"]}

There are a lot of other things that can tell us about a process. See the Erlang docs for process_info for more details.

Get the association with Ecto

In the schema of my post model I have this line:

belongs_to :developer

So a post is associated with a developer. When I have a post struct and try to access the developer I might see this:

> Tilex.Repo.get(Tilex.Post, 42).developer
#Ecto.Association.NotLoaded<association :developer is not loaded>

Getting the developer is now a two step process:

  1. Construct a query based on the association
  2. Use that query to acquire the struct

To construct a query based on the association we can use the Ecto.assoc/2 function:

query = Ecto.assoc(post, :developer)

Then this query is executed with the function:

developer =

There ya go!

erlang memory usage

You might be be curious how much memory your erlang vm is taking. You can get that and more from :erlang.memory. Below is what I get from running this after starting iex normally.

> :erlang.memory
[total: 18133840, processes: 4975616, processes_used: 4974616, system: 13158224,
 atom: 264529, atom_used: 256719, binary: 228728, code: 6640396, ets: 414904]

This list is confusing. All numbers are bytes, so in total 18133840 bytes are allocated to the erlang process. There are two subcategories processes and system and the values of those categories sum to equal the value of total.

The remaining categories are either a component of system or a component of processes.

Listing Files In IEx

When you start an IEx session, you do so in the context of some directory -- the current working directory. This context can be important if you need to do something like import a file. In fact, you may want to know what files are available in the current working directory.

You can list them all out within IEx using ls/0.

iex(1)> ls()
           .git     .gitignore         _build         assets         config
           deps            lib        mix.exs       mix.lock           priv           test

You can also list the contents of some other specific directory by naming it when invoking ls/1.

See h() within IEx for more details.

Use Elixir plug for only some controller actions

Phoenix allows for a flexible request processing pipeline with plugs. Your controllers are basically plugs in the plug pipeline. You can specify plugs that will execute before your controller actions with the plug macro.

defmodule MyApp.ThingController do
  use MyApp.Web, :controller

  plug MyApp.InterestingPlug

You can also specify a guard for this macro that will only enable this plug to be run before certain actions:

plug MyApp.InterestingPlug when action in [:new, :create]

Defining Multiple Clauses In An Anonymous Function

Anonymous functions often take the approach of doing a single thing with the inputs, regardless of their shape or values. There is no need to limit ourselves though. The same pattern matching that we use all over our Elixir programs can be utilized to define multiple clauses in an anonymous function as well.

Consider the following example:

iex> my_function = fn
  {:ok, x} -> "Everything is ok: #{x}"
  {:error, x} -> "There was an error: #{x}"
#Function<6.52032458/1 in :erl_eval.expr/5>

We can then invoke our anonymous function using the bound variable to see what results we get with different kinds of inputs.

iex> my_function.({:ok, 123})
"Everything is ok: 123"
iex> my_function.({:error, "be warned"})
"There was an error: be warned"


The Registry is back

The Registry is a bad Windows dream, something left behind when I switched off Windows for good circa 2011.

It's back. It's a new Elixir 1.4 module where you can store values that you'd like to access globally. Potentially, you want to store a pid of a worker you started. You can store that in the registry like so.

{:ok, pid} = MyWorker.start_link()
supervisor(Registry, [:unique, Registry.WorkerPids])
Registry.register(Registry.WorkerPids, :my_worker, worker_pid)
[{_, found_worker_pid}] = Registry.lookup(Registry.WorkerPids, :my_worker)

A lot is going on here.

  • We start a worker
  • We start the registry process for register Registry.WorkerPids
  • We register the key/value in a specific register (Registry.WorkerPids)
  • We lookup the value in that register with that key

Its important to note that the Registry.WorkerPids symbol is just an atom, not a module. There is no WorkerPids module implementing any special functionality anywhere.

Definitely a lot of ceremony for a key/value store. I expect to find practical uses for it as I experience more complex Elixir systems.

Erlang documentation with `erl -man`

Erlang can be tricky, so documentation is a must, but when you're 30,000 feet high in an airplane with no internet you might regret not having downloaded DashApp and with it all the Erlang documentation.

But it was on your machine the whole time! You have access to all the Erlang documentation with erl -man used like so:

erl -man calendar

Which pops open a man page for the calendar module.

When you are learning Erlang the docs are at your fingertips.

Remove One List From Another

The --/2 operator allows you to subtract two lists, that is, remove all elements in the right list from the left list. Each occurrence of an element is removed if there is a corresponding element. If there is no corresponding element, it is ignored.

Here are some examples.

> [1, 2, 3] -- [2, 4]
[1, 3]
> [:a, :b, :c, :a, :d, :a] -- [:a, :a]
[:b, :c, :d, :a]

This kind of list operation is not particularly efficient, so for large lists it can be quite slow. The following example took several minutes to run.

> Enum.into(1..1000000, []) -- Enum.into(2..1000000, [])

To achieve a true set difference, you'll note that the docs for this operator recommend checking out MapSet.difference/2.

See h Kernel.-- for more details.

Inspect with Label

IO.inspect returns the value you pass in as the first argument. This is great when you want to debug the middle state of a series of piped calls.

|> String.graphemes
|> Enum.each_with_index
|> IO.inspect
|>{letter, i}) -> "#{letter}#{i}" end)
|> Enum.join

Here, inspect will write to stdout the values [{"A", 1}, {"B", 2"}...].

IO.inspect also takes a label option, which decorates the values written to stdout but does not disrupt the piped calls.

|> String.graphemes
|> Enum.each_with_index
|> IO.inspect(label: "Letters with index:")
|>{letter, i}) -> "#{letter}#{i}" end)
|> Enum.join

Which outputs Letters with index: [{"A", 1}, {"B", 2"}...] to stdout.

Jaro Distance determines "closeness" of 2 strings

In Elixir, the String module includes a function named jaro_distance that determines the similarity between two strings:

iex> String.jaro_distance("Chris", "Crhis")
iex> String.jaro_distance("Chris", "Bob")
iex> String.jaro_distance("Chris", "Dennis")

The docs say this works best with short strings. The Jaro distance article on wikipedia has lots of math if you're into that.

Referencing Values In IEx's History

Each time we execute a statement in an iex session, the counter is incremented. These numbers are references to the history of the session. We can use these references to refer to previously executed values using v/1. This is particularly handy for multi-line statements or when we forget to bind to the result of some function.

Consider the following iex session:

iex(1)> :one
iex(2)> 1 + 1
iex(3)> "three" |> String.to_atom()

If we execute v() on its own, it is the same as v(-1) in that it will give us the latest value in the history.

iex(4)> v()

Providing any positive number will refer to the references we see next to each statement.

iex(5)> v(1)

Negative numbers, as we saw with v(-1), will count backwards in the history from where we are.

iex(6)> v(-4)

See h v for more details.

Creating A PID

Often times, when invoking a function that spawns a process, the PID of the spawned process is returned and we bind to it. That PID is a reference to some BEAM process in our system.

We can create our own references using the pid/3 function.

Let's assume we have the following processes, among others, in our system at the moment.

> Process.list |> Enum.reverse |> Enum.take(3)
[#PID<0.284.0>, #PID<0.283.0>, #PID<0.282.0>]

We can create a reference to any of them using the three number parts that they are made up of.

> pid(0, 284, 0)

See, it's alive.

> pid(0, 284, 0) |> Process.alive?

What if we make up a PID that doesn't actually reference any process?

> pid(0, 333, 0) |> Process.alive?

Note: there is also a pid/1 version of the function. See h pid for more details.

Specifying The Phoenix Server Port

Running mix phx.server for a Phoenix project with the default settings will attach the server to port 4000.

If you'd like to use a different port in development, you can change it in config/dev.exs.

config :my_app, MyApp.Web.Endpoint,
  http: [port: 4444],

Alternatively, you can allow it to be configurable from the command line with an environment variable and a fallback port.

config :my_app, MyApp.Web.Endpoint,
  http: [port: System.get_env("PORT") || 4000],


$ PORT=4444 mix phx.server

will launch the server on port 4444.

Check The Installed Version Of Phoenix

Check what the installed version of Phoenix is with the -v flag.

$ mix -v
Phoenix v1.2.0


Compute md5 Hash Of A String

To compute the md5 digest of a string, we can use Erlang's top-level md5 function.

> :erlang.md5("#myelixirstatus")
<<145, 148, 139, 99, 194, 176, 105, 18, 242, 246, 37, 69, 142, 69, 226, 199>>

This, however, gives us the result in the raw binary representation. We would like it in a base 16 encoding, as md5 digests tend to be.

We can wrap (or pipe) this with Base.encode16 to get the result we are looking for.

> Base.encode16(:erlang.md5("#myelixirstatus"), case: :lower)


Counting Records With Ecto

Sometimes you want to know how many records there are in a table. Ecto gives us a couple ways to approach this.

We can use the count\1 function that the Ecto query API provides.

> p in "people", select: count(

16:09:52.759 [debug] QUERY OK source="people" db=1.6ms
SELECT count(p0."id") FROM "people" AS p0 []

Alternatively, we can use the fragment/1 function to use PostgreSQL's count function.

> p in "people", select: fragment("count(*)"))

16:11:19.818 [debug] QUERY OK source="people" db=1.5ms
SELECT count(*) FROM "people" AS p0 []

Lastly, Ecto.Repo has the aggregate/4 function which provides a :count option.

> Repo.aggregate(from(p in "people"), :count, :id)

16:11:23.786 [debug] QUERY OK source="people" db=1.7ms
SELECT count(p0."id") FROM "people" AS p0 []

Unique Indexes With Ecto

You can create a unique index in a migration for one or more columns using the unique_index/3 function.

For example, if you are creating a join table for followers and want to ensure that duplicate follower entries are prevented, you may want to include a unique index like so:

create table(:followers) do
  add :followed_user, references(:users), null: false
  add :following_user, references(:users), null: false

create unique_index(:followers, [:followed_user, :following_user])

Keep in mind that unique_index/3 is a shorthand for index/3 when you set unique: true.

Responding with :stop allows call of `terminate`

A GenServer in Elixir has two lifecycle methods, init and terminate. init is called when the GenServer is started with GenServer.start_link.

What I learned today is that there is a terminate method in case there's any resources that need to be cleaned up when the GenServer is shut down. The terminate method is called when the :stop message is returned from either handle_cast or handle_call:

defmodule Cache do
  use GenServer

  #... a lot of other code

  def handle_cast({:something, 1}, state) do
    IO.puts "This executes first"
    {:stop, "This is my reason for stopping", state}

  def terminate(reason, state)
    IO.puts "Then this executes"

Creating Indexes With Ecto

Using indexes in the right places within relational databases is a great way to speed up queries.

To add a basic index in an Ecto migration, use Ecto.Migration.index\2:

create index(:users, [:email])

Creating a composite index doesn't require jumping through any hoops; just put the relevant column names in the list:

create index(:posts, [:user_id, :title])

See h Ecto.Migration.index for more details.

Custom Phoenix Validations

Today I learned how to write a custom Phoenix model validation. It came from the Phoenix port of this very application, which requires that posts be 200 words or less.

Phoenix doesn't have a word length validation, so I had to make my own. Here it is, minus some irrelevant lines of code:

# web/models/post.ex

def changeset(struct, params \\ %{}) do
  |> cast(params, [:title, :body, :channel_id])
  |> validate_length_of_body

defp validate_length_of_body(changeset) do
  body = get_field(changeset, :body)
  validate_length_of_body(changeset, body)

defp validate_length_of_body(changeset, body) do
  if length(String.split(body, ~r/\s+/)) > 200 do
    add_error(changeset, :body, "should be at most 200 word(s)")

When the post body is greater than 200 words (as defined by splitting on whitespace characters), the validation adds an error to the body field that mimics the errors Phoenix provides for character-length validation failures. Including the (s), which I kind of like.

When the body is short enough, changeset is returned from the function of the same name, a form of success.

Pattern matching FTW.

Range Into List Using Comprehensions

Using an identity comprehension and the :into option, we can easily convert a range into a list.

> for x <- 1..10, into: [], do: x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Check out the docs for the :into option for more details.

Requiring Keys For Structs

When defining a struct in Elixir, we may want to ensure that certain values are provided. We can require that certain keys are used in the creation of a struct with the @enforce_keys attribute. Here is an example of a Name struct.

defmodule Name do
  @enforce_keys [:first, :last]
  defstruct [:first, :middle, :last]

With this defined, we can create a struct that uses all of the keys.

> jack = %Name{first: "Jack", middle: "Francis", last: "Donaghy"}
%Name{first: "Jack", last: "Donaghy", middle: "Francis"}

We can also ignore :middle and just provide the required keys.

> liz = %Name{first: "Liz", last: "Lemon"}
%Name{first: "Liz", last: "Lemon", middle: nil}

We cannot, however, omit any of the keys specified in @enforce_keys. If we do omit any of them, Elixir will raise an error.

> tracy = %Name{first: "Tracy"}
** (ArgumentError) the following keys must also be given when building struct Name: [:last]
    expanding struct: Name.__struct__/1
    iex:6: (file)

Virtual Fields With Ecto Schema

If you'd like to include a particular key-value pair in an Ecto changeset, it needs to be included as a field in the schema. In the case of something akin to a password field, you want to be able to perform validations against it, but the password itself does not have a column in the database. In other words, you want to use the password in memory as part of the validation process but not save it to the database. To accomplish this, you need to specify that it is a virtual field.

schema "users" do
  field :username, :string
  field :password_digest, :string
  field :password, :string, virtual: true

With that schema, you can then validate the :password and transform it into the corresponding :password_digest field.

def registration_changeset(model, params) do
  |> changeset(params)                  # do other standard validations
  |> cast(params, [:password])          # include :password in the changeset
  |> validate_length(:password, min: 8) # validations
  |> put_pass_hash()                    # transform into :password_digest

Root Directory Of A Project

Do you need the root directory of an elixir project? The File.cwd!/0 function can help.

iex> File.cwd!

Keep in mind though, this will only work reliably with projects that are compiled using Mix.


Pivoting a 2-dimensional list

In one of the exercises, a grid is represented by a list of lists where each inner list represents a row.

The exercise then asks you to pivot the grid, that is, transform the list of lists so that each list represents a column.

From someone else's solution I learned that an easy way to conduct this transform is to use and Tuple.to_list.

grid = [[1,2,3, 4], [1,2,3, 4], [1, 2, 3, 4]] 
# [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]

Tuple's to_list method is needed because returns an array of tuples.

Merge maps with a callback

Merging two maps together is something I'm familiar with:

iex> Map.merge(%{a: 1, b: 2}, %{c: 3})
%{a: 1, b: 2, c: 3} 

But this function suffers from a unilateral decision that's made when a key in the first argument also exists in the second argument. The value from the first map always overwrites the value from the second.

iex> Map.merge(%{a: 1, b: 2, c: 100}, %{c: 3})
%{a: 1, b: 2, c: 100}

But Elixir's Map module has a merge function that takes a function as an additional argument. It lets you decide what to do in case of a key conflict. You could write this function so that the second argument overwrites the first or better yet add the two values together.

iex> Map.merge(%{a: 1, b: 2, c: 100}, %{c: 3}, fn(k, v1, v2) -> v1 + v2 end)
%{a: 1, b: 2, c: 103}

Three data types that go `into` a Map

Enum.into can be used to put different types of things into different types of collections. For instance I can put elements from one list into another list.

iex> Enum.into([4], [1,2,3])
[1, 2, 3, 4]

It works with Maps too and there's different types of things than can go into a map. A map can certainly go into another map:

iex> Enum.into(%{"a" => 1}, %{"b" => 2})
%{"a" => 1, "b" => 2}

Keyword lists also go into a map:

iex> Enum.into([a: 1], %{"b" => 2})
%{:a => 1, "b" => 2}

And lists of tuples also go into a map:

iex> Enum.into([{"a", 1}], %{"b" => 2})
%{"a" => 1, "b" => 2}

But only when there are two elements in the tuple:

iex(32)> Enum.into([{"a", 1, 3}], %{"b" => 2})
** (ArgumentError) argument error
    (stdlib) :maps.from_list([{"a", 1, 3}])
    (elixir) lib/enum.ex:1072: Enum.into/2

Using assigned value later in same pattern match

I have an array of character lists.

['apple', 'aardvark']

And I want to make sure that each of these two items has the same beginning letter.

I can do this with pattern matching because variables can be reused in an assignment.

iex > [[c | _], [c | _]] = ['apple', 'aardvark']
['apple', 'aardvark']
iex > c

Here's what happens when the first letter does NOT match.

iex > [[c | _], [c | _]] = ['apple', 'hamster']
** (MatchError) no match of right hand side value: ['apple', 'hamster']

Render A Template To A String

Templates in a Phoenix application ultimately get compiled to functions that can be quickly rendered with the necessary data. We can take a look at how a template will be rendered using Phoenix.View.render_to_string/3.

First, we need a template:

# user.html.eex
<h1><%= @user.first_name %></h1>
<h5><%= @user.username %> (<%= %>)</h5>

We can then render that template for the view with some user:

> user = %User{first_name: "Liz", last_name: "Lemon", username: "llemon", email: ""}

> Phoenix.View.Render_to_string(MyApp.UserView, "user.html", user: user)
"<h1>Liz</h1>\n<h5>llemon (</h5>\n"

Run ExUnit tests in the order they are defined

You might have a test module like this.


defmodule TestOrderTest do
  use ExUnit.Case

  test "first" do
    assert true

  test "second" do
    assert true

And when you run it, second runs before first!

In general this is fine, because every test should pass no matter which one runs first. In certain circumstances however, lets say you're working through some challenges, you might want them to run in order.

To do so include the configuration seed: 0

Elixir.configure seed: 0

And tackle every test in the order they've been given to you!

Do You Have The Time? - Part 2

In Do You Have The Time?, I demonstrated a way of using an Erlang function to get at and work with time in Elixir. As of Elixir 1.3, there is now a Time module that provides a sigil and some functions for working with time.

We can use Elixir's Time module to simplify the example from the previous iteration of this TIL:

defmodule TickTock do
  def current_time do
    |> Time.to_string

> TickTock.current_time

Check For A Substring Match

Using Erlang's :binary.match function, you can easily check if a string has a matching substring.

> :binary.match("all food is good", "foo")
{4, 3}
> :binary.match("all food is good", "bar")

As you can see, the return value on a successful match is a tuple with the index of where the match starts and the length of the match. If there is no match, the :nomatch atom is returned.

See the match/2 and match/3 docs for more details.


Do You Have The Time?

Elixir doesn't come with any standard ways of getting at or working with time. There are packages like Timex out there that we can pull in to our projects. However, if we don't have need for a full-featured date/time library, we can opt for a simpler solution.

Erlang can give us the time.

defmodule TickTock do
  def current_time do
    {hh,mm,ss} = :erlang.time

> TickTock.current_time

Documentation Lookup With Vim and Alchemist

Which argument position is the accumulator for Enum.reduce/3?

How does group_by work?

I find myself fairly frequently jumping from vim to Chrome to do Google searches for Elixir standard lib documentation. It gets the job done, but it is kinda slow and I'd prefer to avoid the context switch.

With alchemist.vim, Elixir documentation lookup is at your finger tips. Just move the cursor over the module or function you are curious about and hit K (from normal mode).

Curious about Enum.reduce? Type it out in your current Vim buffer, move the cursor over it, and hit K.

Elixir with macro `<-` and `=`

So Elixir with macro accepts Matching clauses <- and Bare expressions =. Both match patterns and do not leak variables assigned inside these structures.

with {:ok, width} <- Map.fetch(%{width: 10}, :width),
  do: {:ok, 2 * width}
#=> {:ok, 20}

with {:ok, width} = Map.fetch(%{width: 10}, :width),
  do: {:ok, 2 * width}
#=> {:ok, 20}

So what is the difference between these?

When a match fails, matching clauses <- returns failed result but bare expressions = raises a MatchError:

with {:ok, width} <- Map.fetch(%{height: 10}, :width),
  do: {:ok, 2 * width}
#=> :error

with {:ok, width} = Map.fetch(%{height: 10}, :width),
  do: {:ok, 2 * width}
#=> ** (MatchError) no match of right hand side value: :error

Another difference is that when guard is only available for matching clause.

with {:ok, width} when is_number(width) <- Map.fetch(%{width: 10}, :width),
  do: {:ok, 2 * width}
#=> {:ok, 20}

Updating Values In A Map

When working with maps in any language, you often need a way to update key-value pairs. Furthermore, you will need a way to handle keys that are not already present in the map, generally associating some default value.

In Elixir, the Map module provides the get_and_update/3 function as a way of accomplishing such a task.

Let's use a score counting example to see it in action:

> scores = %{}
# jake scores a point
> {_, scores} = Map.get_and_update(scores, :jake, fn(x) -> {x, (x || 0) + 1} end)
{nil, %{jake: 1}}
# chris scores a point
> {_, scores} = Map.get_and_update(scores, :chris, fn(x) -> {x, (x || 0) + 1} end)
{nil, %{chris: 1, jake: 1}}
# jake scores another point
> {_, scores} = Map.get_and_update(scores, :jake, fn(x) -> {x, (x || 0) + 1} end)
{1, %{chris: 1, jake: 2}}
# final scores
> scores
%{chris: 1, jake: 2}

We use (x || 0) + 1 as a way of providing an initial score for new keys.

The update function is expected to return a tuple with the original value and the updated value.

See the docs for more details.

Elixir Exceptions are Structs

Elixir Exceptions are actually Structs:

Map.keys %RuntimeError{}
#=> [:__exception__, :__struct__, :message]

#=> "runtime error"

This is also true when you define an Exception with defexception.

Pattern Match and ++ operator

Today I learned that ++ operator should not be used on pattern matching.

This works with Lists of integers, but fails on compilation time for other content type.

[1] ++ [2] = [1, 2] #=> [1, 2]

[:foo] ++ [:bar] = [:foo, :bar] #=> ** (CompileError): illegal pattern
[foo: 1] ++ [bar: 2] = [foo: 1, bar: 2] #=> ** (CompileError): illegal pattern

Elixir Binaries and Bit Strings

Today I learned that in Elixir Binary is a sub type of Bit String with all elements using a multiple of 8 bits.

"a" # => "a"
?a # => 97
<<97>> # => "a"
is_bitstring <<97>> # => true
is_binary <<97>> # => true
is_bitstring <<97::4>> # => true
is_binary <<97::4>> # => false
is_binary <<97::16>> # => true
  • So String is a UTF-8 Binary.
  • And Binary is a multiple 8 bits Bit String.

Pipe into operators

Since Elixir operators are macros defined on Kernel or in a submodule of Kernel, we can pipe into them when we call the function on Kernel:

true |> || false # this raises a syntax error

true |> Kernel.||(false) # valid Elixir

Real world example from the Phoenix source:

Binary Representation Of A String

A common trick in Elixir is to concatenate the null byte <<0>> to a string to see its inner binary representation.

A couple example of this can be seen in the following snippet of code:

> "hello" <> <<0>>
<<104, 101, 108, 108, 111, 0>>
> "ƒå®øü†" <> <<0>>
<<198, 146, 195, 165, 194, 174, 195, 184, 195, 188, 226, 128, 160, 0>>


Reversing A List

To efficiently work with and transform lists in Elixir, you will likely need utilize a list reversing function from time to time. Your best bet is to reach for the Erlang implementation which is available as part of the lists module.

Here are a couple examples of how to use it:

> :lists.reverse([1,2,3])
[3, 2, 1]
> :lists.reverse([1, :a, true, "what", 5])
[5, "what", true, :a, 1]

Note: though I said _transform_ lists above, what is actually going on is that a new version of the list representing my transformation is being created, per Elixir's functional nature.


I discovered a pretty cool Elixir function this weekend, Enum.chunk_by.

Backstory: I wanted to group a list of strings by equality, while preserving the list order.

Enum.chunk_by takes an enumerable and a function, and breaks that enumerable into an enumerable when the function returns a new or different result.

Here's a simple example:

iex> Enum.chunk_by(['A', 'A', 'A', 'B', 'A'], fn(l) -> l end)
[['A', 'A', 'A'], ['B'], ['A']]

Anytime l changes, a new list is created.

Slightly more complex:

iex> Enum.chunk_by([1, 2, 3, 4, 5], fn(n) -> rem(n, 3) == 0 end)
[[1, 2], [3], [4, 5]]

The function only returns something different (true) on 3, so 3 is assigned to its own list.

Simplify System.cmd with W sigil

Say we have the following shell command to get the the unix timestamp of the last commit:

$ git log -1 --date=short --pretty=format:%ct


In elixir. One might do it like so:

System.cmd("git", ["log", "-1", "--date=short", "--pretty=format:%ct]) 
|> elem(0)

#=> "1470067380"

And here is just a simpler syntax for the same thing:

System.cmd("git", ~w[log -1 --date=short --pretty=format:%ct])
|> elem(0)

#=> "1470067380"

This is just a little clean and feels more like the original command.

Ruby-Like `split` in Elixir

Elixir's split function is a bit different from the Ruby version you might be familiar with.

Here's Ruby's split:

2.1.0 :001 > "FOOBAR".split("")
 => ["F", "O", "O", "B", "A", "R"]

And Elixir's:

iex(1)> String.split("FOOBAR", "")
["F", "O", "O", "B", "A", "R", ""]

Whoa, what's that extra "" doing in there? Drink in the Elixir. A small amount of message board reading has led me to conclude this was very deliberate and isn't going to be changed.

Here's one way to get a Ruby-like split:

iex(1)> String.split("FOOBAR", "", trim: true)
["F", "O", "O", "B", "A", "R"]

alias is lexically scoped

Aliases are lexically scoped, allowing you to alias a module inside of a function and that alias will only exist in that function's scope. Also TIL: You can even alias over Elixir standard lib module names.

defmodule Cartography do
  def north_america do
   alias Earth.NorthAmerica.Map
   #Map is now Earth.NorthAmerica.Map
   # You can get to the normal Map module using Elixir.Map

  def foo do
    #Map is still Elixir.Map

.iex.exs file

A .iex.exs file at the root of your elixir project will be executed when you start your IEX session. Great for aliasing!


one = 1

alias MyApp.{Foo, Bar}

In your IEx session the variable one will be in scope and Foo and Bar will be aliased.

Named Captures with Elixir Regular Expressions

I can't believe I'm just now learning about this! How neat!

iex(0)> string = "Here is my phone number: 999-111-1234"
"Here is my phone number: 999-111-1234"
iex(1)> regex = ~r/number: (?<phone>[\d|-]+)/
~r/number: (?<phone>[\d|-]+)/
iex(2)> Regex.named_captures(regex, string)
%{"phone" => "999-111-1234"}

Write a regex capture with ?<> in the beginning and get back a map of your captures with Regex.named_captures/2

Invoke Elixir Functions with Apply

I had a weird problem yesterday: I wanted to pass a function into another function and then invoke it, all for the sake of a friendly API.

Elixir's apply to the rescue. Here's the rough implementation.

defmodule Example do
  def do_things(index, rotation, operator) do
    apply(Kernel, operator, [index, rotation])

iex> Example.do_things(10, 20, :+)
iex> Example.do_things(10, 20, :-)

apply also accepts your own functions:

defmodule Example do
  def do_things(index) do
    apply(__MODULE__, :make_bigger, [index])

  def make_bigger(a) do
    a * 10000

iex> Example.do_things(100)

The module name (Example) will work in place of __MODULE__, if you prefer. This seems like a pretty powerful feature.

Transform values when using SweetXML xmap

Assume I have the following XML

xml = """

I can write a small module to map this to something really cool.

defmodule XmlMapper do
  import SweetXml
  @schema [
      names: [ ~x[//response/users/user]l,
        name: ~x[concat(./firstName, " ", ./lastName)]s |> transform_by(&String.upcase/1)

  def map(xml_string) do
    SweetXml.xmap(xml_string, @schema)

.map will find a list of user elements, concatenate the firstName and lastName, then upcase the whole thing and return it in a map.

%{names: [%{name: "MICAH COOPER"}, %{name: "JOE HASHROCKET"}]}

That's doing a lot with a little.

Tab Completion in IEx

IEx has tab completion of library functions, just like IRB. To see all the built-in Stream functions, just type Stream. and hit TAB, and you'll get output like this:

iex(1) Stream.
Reducers        chunk/2         chunk/4         chunk_by/2
concat/1        concat/2        cycle/1         dedup/1
dedup_by/2      drop/2          drop_while/2    each/2
filter/2        filter_map/3    flat_map/2      interval/1
into/3          iterate/2       map/2           reject/2
repeatedly/1    resource/3      run/1           scan/2
scan/3          take/2          take_every/2    take_while/2
timer/1         transform/3     transform/4     unfold/2
uniq/2          with_index/2    zip/2

This is a nice feature when you're experimenting in the REPL.

h/t Micah Cooper

Find and Open Port with Elixir

iex(1)> {:ok, port} = :gen_tcp.listen(0, []) #listen on an available port
{:ok, #Port<0.1465>}
iex(2)> {:ok, port_number} = :inet.port(port) #get the port number of that port
{:ok, 63470}
iex(3)> port_number #here is the port number!
iex(4)> Port.close port #go ahead and close that port if you want

Useful for maybe automating the deployment of a plug app.

An Agent reference can be pid or name.

Each function of the Agent module takes an agent as the first argument:

get(agent, fun, timeout \\ 5000)

but this can be a couple of different things. The documentation defines the agent type as:

agent :: pid | {atom, node} | name

#The agent reference

name ::
  atom |
  {:global, term} |
  {:via, module, term}

#The agent name

So really five different types of values are valid. The pid is a value returned from calling start_link.

> {:ok, agent_pid} = Agent.start_link(fn -> [:thing] end)
> Agent.get(agent_pid, fn (state) -> hd(state) end)

The agent can be referenced by a name atom also. In the documentation example that name atom is the __MODULE__ for the module that wraps access to the agent. The name for the agent is declared by passing a name option into the start_link function call.

> Agent.start_link(fn -> [:thing] end, name: __MODULE__)
> Agent.get(__MODULE__, fn (state) -> hd(state) end)

I'm note sure about the {:global, term} and {:via, module, term} values that seem to be valid. I would love to see examples for those.

Dynamically Generating Atoms

Atoms are constants where their name is their own value.

The use of atoms like :ok and :error show up all over the place in Elixir. These are atoms that tend to be statically defined. Atoms can also be dynamically defined using string interpolation.

For example, I can generate a handful of atoms by mapping over a range of integers.

>, &(:"some_atom_#{&1}"))
[:some_atom_1, :some_atom_2, :some_atom_3, :some_atom_4, :some_atom_5]

Note: atoms are not garbage collected. If you dynamically generate atoms in excess, you may run your VM out of heap space.

Periodic messages in Elixir

Today I needed to implement a task that happens once every 24 hours. I immediately thought, well this should be a cron job, but my co-worker suggested using the send_after method in a GenServer instead.

    Process.send_after(self, {:"$gen_cast", :get_data}, interval)

The third argument is a milliseconds argument that determines when the call will be processed. The $gen_cast is a hackish type of thing to get the GenServer to handle the call with handle_cast.

The periodism should start in the init and whenever handle_cast is called, it should schedule a new time that the message will be sent.

  def init(state) do
    Process.send_after(self, {:"$gen_cast", :get_data}, interval)
    {:ok, state}

  def handle_cast(:get_data, state) do
    Process.send_after(self, {:"$gen_cast", :get_data}, interval)
    {:noreply, state}

H/T Micah Cooper

`hd` in Guard Tests

The hd method in Elixir returns the head of a list. It's kind of like List.first, but raises an error on an empty list.

iex(0)> hd [1,2,3]
iex(1)> hd []
** (ArgumentError) argument error

Browsing the docs, I learned something interesting: hd is allowed in guard tests.

Here's a contrived implementation of this behavior:

# example.ex
defmodule TestModule do
  def header(list) when hd(list) == 1, do: IO.puts "We did it"
iex(0)> TestModule.header([1,2,3])
We did it

When the guard's conditions aren't met, an error is raised:

iex(1)> TestModule.header([2,3,4])
** (FunctionClauseError) no function clause matching in TestModule.header/1
    iex:13: TestModule.header([2, 3, 4])

h/t Chris Erin & Micah Cooper

Assert An Exception Is Raised

Elixir's ExUnit comes with a number of different ways to make assertions in your tests. One of those functions is assert_raise which allows you to test that a particular exception is raised when the given function is invoked.

Using assert_raise/2 looks something like this:

assert_raise FunctionClauseError, fn ->
  Enum.chunk([1,2,3], 0)

The assert_raise/3 form is also available which allows you to test both the type of exception and the resulting message.

assert_raise FunctionClauseError, ~r/^no function clause matching/, fn ->
  Enum.chunk([1,2,3], 0)

Using the regex sigil for the second argument is generally a good way to go to keep tests from getting too brittle.

Capture IO.puts in ExUnit tests

Whenever writing a CLI you often have to communicate something to the user via IO.puts, and while some languages make it complicated to capture output in a test, Elixir makes it extremely straight-forward.

All we have to do is import the ExUnit.CaptureIO module into our test which exposes the capture_io method.



defmodule MyApp.CLI do
  def main(argv), do
    # parse args ...
    # return :help if the -h switch is supplied
    # pass to process
    |> parse_args
    |> process

  def process(:help) do
    IO.puts "usage: my_app <arg1> <arg2>"

IO capturing test:

defmodule CliTest do
  use ExUnit.Case

  import ExUnit.CaptureIO

  test "prints usage instructions when the help switch is supplied" do
    execute_main = fn ->

    assert capture_io(execute_main) =~ "usage:"

For more information read the ExUnit.CaptureIO documentation

String Interpolation With Just About Anything

Coming to Elixir from Ruby, I am used to being able to interpolate literally anything into a string. In Elixir, this is not the case.

By default, it handles strings, atoms (including nil, true, false and module name aliases like String – which are all just atoms behind the scenes), integers, floats, and some lists. That's it.

There are two approaches you can take to interpolate everything else into a string. The easier approach is to use Kernel.inspect/2.

> IO.puts "A map #{inspect %{a: 1, b: 2}}"
A map %{a: 1, b: 2}

The other approach is to implement the String.Chars protocol for the thing that you are trying to print. You can read more about that in Elixir String Interpolation for Rubyists.

Pattern Matching In Anonymous Functions

Pattern matching shows up everywhere in Elixir, even where you may not be expecting it. When declaring an anonymous function, you can use pattern matching against different sets and shapes of input parameters to invoke different behaviors.

Here is an example of how you might use this:

> handle_result = fn
  {:ok, result} -> IO.puts "The result is #{result}"
  :error -> IO.puts "Error: couldn't find anything"
#Function<6.50752066/1 in :erl_eval.expr/5>

> Map.fetch(%{a: 1}, :a) |> handle_result.()
The result is 1
> Map.fetch(%{a: 1}, :b) |> handle_result.()
Error: couldn't find anything


Quitting IEx

There are two ways to quit out of an Interactive Elixir shell. The standard way is with Ctrl-c. This gives you a list of options, one of which is a for abort. This will terminate your IEx session and drop you back on the command line where the process started.

Additionally, IEx also understands Ctrl-\ which is control key that will terminate just about any interactive environment. This command will cause IEx to immediately exit with no prompt.

Note: IEx does not, however, respond to Ctrl-d.


Shell History in IEx

Do you like Elixir, but want history in your interactive shell, just like Ruby and other languages? I've got you covered.

Check out erlang-history. It's a must-have.

Here's the abridged version:

$ git clone
$ cd erlang-history
$ sudo make install

Fire up IEx and enjoy.

Create A Date With The Date Sigil

Elixir 1.3 introduced a new sigil for creating dates, ~D. It works in the same way as Date's new/3 function producing the Date struct with each of the date parts.

> ~D[2016-01-01]
> ~D[2016-01-01].year
> ~D[2016-01-01].month
> ~D[2016-01-01].day

Change resource param in Phoenix routes

Phoenix, like Rails, gives you the option to specify a resource in your routes in order to generate the typical CRUD actions we deal with in a controller. The dynamic segment which identifies the resource is :id by default.

resources "orders", OrderController

The update route would look like this if we run mix phoenix.routes.

order_path  PATCH  /orders/:id    MyApp.OrderController :update

If our table doesn't use id as a primary key, or we want to change the field we use to find our resource, we can specify it as an option in our route:

resources "orders", OrderController, param: "some_field"

Now our route is updated:

order_path  PATCH  /orders/:some_field    MyApp.OrderController :update

Execute Raw SQL In An Ecto Migration

If you are performing a database migration with Ecto, perhaps the most straightforward approach is to use Ecto's DSL. However, the DSL may not always be the best choice. Being able to write raw SQL gives you more control. It will also enable you to use database features that may not be directly or easily available through the DSL.

Raw SQL can be included in a Ecto migration with a combination of Elixir's heredoc syntax and the Ecto.Migration#execute/1 function. You'll also need to provide both an up and down function to ensure that your migrations are reversible.

defmodule MyApp.Repo.Migrations.CreatePostsTable do
  use Ecto.Migration

  def up do
    execute """
      create table posts (
        id serial primary key,
        title varchar not null,
        body varchar not null default '',
        inserted_at timestamptz not null default now(),
        updated_at timestamptz not null default now()

  def down do
    execute "drop table posts;"

Word Lists For Atoms

The ~w sigil works similarly to Ruby's %w (word array notation). It allows you to create a list of words (i.e. strings).

> ~w(one two three)
["one", "two", "three"]

It sets itself apart though with some modifiers. The default behavior matches the s modifier (for strings).

> ~w(one two three)s
["one", "two", "three"]

Where it gets more interesting is with the a modifier allowing you to create a list of atoms.

> ~w(one two three)a
[:one, :two, :three]

Note: there is a third modifier, c, for char lists.

> ~w(one two three)c
['one', 'two', 'three']


3 parts of routing a websocket

First, there's a socket declaration in the lib/appname/endpoint.ex file.

  socket "/socket", AppName.UserSocket

Second, there's a transport declaration in the web/channels/user_socket.ex file.

  transport :ws, Phoenix.Transports.WebSocket

Now, the websocket will be available at the url ws://localhost:4000/socket/ws the final path segment of the url being added by the first argument of the transport declaration.

Finally, the channel topic is also declared in the user_socket.ex file.

channel "app_topic:*", AppName.MyChannel

Now every json body that has a topic attribute of app_topic will be routed to MyChannel.AppName where it will be handled appropriately based on the event attribute.


List Functions For A Module

During an iex session, I can do a little introspection on modules using either the __info__/1 function or Erlang's module_info/0 function. In particular, I can pass :functions to either one to get a list of the functions for that module.

This is what __info__/1 looks like for the functions of the List module:

> List.__info__(:functions)
[delete: 2, delete_at: 2, duplicate: 2, first: 1,
 flatten: 1, flatten: 2, foldl: 3, foldr: 3, insert_at: 3,
 keydelete: 3, keyfind: 3, keyfind: 4, keymember?: 3,
 keyreplace: 4, keysort: 2, keystore: 4, keytake: 3,
 last: 1, replace_at: 3, to_atom: 1, to_existing_atom: 1,
 to_float: 1, to_integer: 1, to_integer: 2, to_string: 1,
 to_tuple: 1, update_at: 3, wrap: 1, zip: 1]


Getting a date

Elixir 1.3 has introduced calendars and calendar types. Lets check out how to get a Date type!

You can use the new function and pass in year, month and day separately.

iex >, 6, 28)
{:ok, ~D[2008-06-28]}

If you want a nonsensical date you'll get an :error atom back.

iex >, 6, 31)
{:error, :invalid_date}

Elixir knows how to handle ISO8601 date formatted strings. Don't forget to zero pad that month value!

iex > Date.from_iso8601("2008-6-28")
{:error, :invalid_format}
iex > Date.from_iso8601("2008-06-28")
{:ok, ~D[2008-06-28]}

To support Erlang the from_erl function will accept a tuple.

iex > Date.from_erl({2008, 6, 28})
{:ok, ~D[2008-06-28]}

It's interesting that the date is inspected as a sigil.

iex > {:ok, d} = Date.from_erl({2008, 6, 28})
{:ok, ~D[2008-06-28]}
iex > d

Hey you can create a date with the new sigil syntax!

iex > ~D[2008-06-28]

Microbenchmarking elixir with Benchee

There is a hex package to help facilitate benchmarking in elixir. Below is an example of how to compare flat_map to map().flatten(). Example stolen straight from the README.

list = Enum.to_list(1..10_000)
map_fun = fn(i) -> [i, i * i] end{time: 3},
             [{"flat_map", fn -> Enum.flat_map(list, map_fun) end},
              fn -> list |> |> List.flatten end}])

Matching *within* function parameter declaration

The below contains a matching expression within the function declaration:

iex > defmodule Hulk do
... > def print({1, a} = tt) do
... > IO.inspect(a)
... > IO.puts("**********")
... > IO.inspect(tt)
... > end
... > end

This allows the function access to the variable that was bound while matching and the full value passed in to the function. It returns:

iex > Hulk.print({1, 3})
{1, 3}

This is particularly useful for Maps which is the only datatype to support partial matching (eg %{a: a} = %{a: 1, b: 2}) so that the unknown and unmatched portion of the map will be available.

This is a common idiom in pheonix while declaring actions in controllers:

def show(conn, %{"messenger" => messenger} = params) do

The above is from the pheonix docs

Two anonymous functions in one

Elixir has anonymous functions, and function pattern matching, and to accommodate the two concepts the language has the facility to do both at the same time.

alphaIndex = fn ("a") -> 0;  ("b") -> 1; (letter) -> :unknown end

# returns 0
# returns 1
# returns :unknown

Using __using__ for use with the `use` macro

You might run across the use macro while doing something like.

use GenServer

This sets up the module to be able to do special things with the special module GenServer.

Behind the scenes GenServer implements

defmacro __using__(_opts) do

to ensure that the module is setup correctly for use with GenServer.

You can experiment with implementing __using__ inside of IEX like so:

iex > defmodule Fruit do
... > defmacro __using__(_opts) do
... > quote do
... > IO.puts "Good to see you've added Fruit to your meal"
... > end
... > end
... > end

iex > defmodule Meal do
... > use Fruit
... > end
"Good to see you've added Fruit to your meal"

Binary pattern matching

You might be familiar with the most popular form of Elixir pattern matching involving tuples:

iex > {:ok, x} = {:ok, 1000}
{:ok, 1000}
iex > x

You can also pattern match binaries:

iex > <<1, y, 2>> = <<1, 255, 2>>
<<1, 255, 2>>
iex > y

This gets powerful when you're able to match binary formats.

iex > <<x :: binary-1, y :: binary-2, z :: binary>> = <<1, 255, 254, 2>>
<<1, 255, 254, 2>>
iex > x
iex > y
<<255, 254>>
iex > z

Here's an article about using binary pattern matching to parse a png file.

Observe the erlang vm with :observer

Elixir and Erlang can have fairly complex process organization structures, but they can be inspected with the observer tool.

You can start the observer tool with:

iex > :observer.start

And then you'll have access to a gui with tabs labled:


Load Charts

Memory Allocations



Table Viewer

Trace Overview

Determine type? no. Get info tho with `i`

There is no direct way to get a variable type in Elixir. For instance type("") is not something that exists although there are 15 Kernel methods for specific type determination such as:

iex > is_number(1)
iex > is_binary("") # Note that elixir checks for binary instead of string, a string is a binary.
iex > is_atom(:hey)

There is an i function available only in iex that will print out useful information about a variable.

iex > i("")
Data type
Byte size
  This is a string: a UTF-8 encoded binary. It's printed surrounded by
  "double quotes" because all UTF-8 encoded codepoints in it are printable.
Raw representation
Reference modules
  String, :binary

It's implemented as a protocol check it out.

I discovered it here.

Weird Operator Uses in Elixir

= is match, not assignment (sometimes they're equivalent)

<> is string concatenation

[a | b] is a pipe used within squares and appends the left hand side to the right hand side when the right hand side is a list.

++ is an append operator for lists

[1, 2, 3] ++ [4] == [1, 2, 3, 4]

-- is a subtraction operator for lists.

[1, 2, 3] -- [1, 2] == [3]

in checks to see if an element is included in a list.

1 in [1] == true

=== works with numbers and returns false when comparing numbers of different types that would otherwise be equivalent.

(1 === 1.0) == false; (1 == 1.0) == true

^ is the pin operator, it switches a variable from assignable to matchable.

iex > a = 1; {^a, b} = {1, 2};
{1, 2}
iex > a = 1; {^a, b} = {2, 2};
** (MatchError) no match of right hand side value: {2, 2}
iex > a = 1; {a, b} = {2, 2};
{2, 2}

Accessing a single element of a list by index

Getting a element form a list by index is a common language idiom.

In ruby you would use the squares [] method (similar to Java, C#, etc.).

> [:a, :b, :c, :d][2]

But Elixir is not object oriented and instead provides the Enum module that has many functions that can operate on a list. Three functions return an element by index.

iex >[:a, :b, :c, :d], 2)
iex > Enum.fetch([:a, :b, :c, :d], 2)
{ :ok, :c }
iex > Enum.fetch!([:a, :b, :c, :d], 2)
{ :ok, :c }

They behave differently when the index doesn't correspond to the list.

iex >[:a, :b, :c, :d], 9999)
iex > Enum.fetch([:a, :b, :c, :d], 9999)
iex > Enum.fetch!([:a, :b, :c, :d], 9999)
** (Enum.OutOfBoundsError) out of bounds error
    (elixir) lib/enum.ex:722: Enum.fetch!/2

I don't understand how the statuses (:ok, :error) might be used in application code yet by I'm curious and can't wait to find out!

Three ways to compile Elixir

1: Use the c function in iex

iex> c('lib/funkymath.ex')

2: When opening iex pass the module as a command line argument

$ iex lib/funkymath.ex

3: Use the mix command line utility.

$ mix compile

This last option creates some artifacts that you can then use.

Ecto 2.0 ownership timeout #myelixirstatus

Ecto 2.0, gives us concurrent testing against the DB by allowing an Elixir process to own a database connection. The default time releases the connection pretty quick, so it's not suitable for debugging anything thats non-trivial.

We can change the timeout in our config/test.exs

config :my_app, MyApp.Repo,
  adapter: Ecto.Adapters.Postgres,
  ownership_timeout: 60_000

Require file outside of load path

If an Elixir module hasn't been compiled/loaded already, we can't just require/import/use it. Use:

Code.require_file "foo.exs", __DIR__

Hound -> Create, Open, then Delete a Screenshot

While running integration tests with Hound, I wanted my test to take a screenshot, open it, and remove the screenshot after the test runs.

def screenshot do
  shot = take_screenshot
  System.cmd("open",  [shot])
  on_exit fn ->
    :timer.sleep 500
end a charm :)

Expose Internal Representation

Elixir is a language that has strong support for metaprogramming. It provides easy access to an internal representation of the code in the form of an Abstract Syntax Tree (AST) using maps and keyword lists. The quote macro is used to expose this internal representation.

> quote do: 2 * 2
{:*, [context: Elixir, import: Kernel], [2, 2]}
> quote do: 2 * 2 == 4
{:==, [context: Elixir, import: Kernel],
 [{:*, [context: Elixir, import: Kernel], [2, 2]}, 4]}


Append To A Keyword List

If you have two keyword lists, you can append them like so:

> a = [a: 1]
[a: 1]
> b = [b: 2]
[b: 2]
> a ++ b
[a: 1, b: 2]

But what if something a bit more programmatic is happening and you are building up the additions to the keyword list based on variables?

> x = :x
> c = a ++ [x 5]
** (CompileError) iex:5: undefined function x/1
    (stdlib) lists.erl:1353: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3

That makes elixir think x is some function when in fact it is just a variable containing the keyword :x.

Simply adding a comma doesn't quite do it either.

> c = a ++ [x, 5]
[{:a, 1}, :x, 5]

We need to wrap the internal part with curly braces to create the tuple that can then be appended to a.

> c = a ++ [{x, 5}]
[a: 1, x: 5]

Get the last record with Ecto x in MyApp.Model, order_by: [desc:], limit: 1)

Recompile in iex session

After editing a module, we can recompile the file containing that module inside of an iex session using the r command.

defmodule Bar do
 # code and stuff

defmodule Foo do
  # code and stuff
iex> r Foo
# {:reloaded, Foo, [Bar, Foo] }

Clear screen in iex

Since v0.10.1, Elixir has had a clear function in iex for clearing the screen. On a Mac, you can also do Command + K.

Pry in Elixir Phoenix

One of my favorite debugging tools in Ruby is Pry, so I wanted to find something similar to use when developing Phoenix applications. Thankfully Elixir has pry built in!

To use it in Phoenix, simply include this line wherever you want to pry:

require IEx; IEx.pry

I then had to start my server in an IEx session to get the pry to work (I've read this will be fixed soon):

iex -S mix phoenix.server

When you hit that function, you will be asked to confirm that you want to Pry

Request to pry #PID<0.331.0> at web/controllers/user_controller.ex:7. Allow? [Yn]

Confirm by typing Y and you will be good to pry away!