Today I Learned

A Hashrocket project

Accumulating Attributes In Elixir

Typically, if you declare an attribute twice like this:

@unit_of_measure :fathom
@unit_of_measure :stone

The second declaration will override the first:

IO.inspect(@unit_of_measure)
# :stone

But by registering the attribute by calling register_attribute you get the opportunity to set the attribute to accumulate. When accumulating, each declaration will push the declared value onto the head of a list.

defmodule TriColarian do
  @moduledoc false

  Module.register_attribute(__MODULE__, :colors, accumulate: true)

  @colors :green
  @colors :red
  @colors :yellow

  def colors do
    @colors
  end
end

TriColarian.colors()
# [:yellow, :red, :green]

At compile time, perhaps when executing a macro, you have the opportunity to dynamically build a list.

I learned this when Andrew Summers gave a talk on DSLs at Chicago Elixir this past Wednesday. You can see his slides here

Looking for help? Elixir is quickly gaining momentum for web applications that need concurrency, performance, and the ability to connect to many different clients. The developers at Hashrocket are learning along with the rest of the development community that Elixir and Phoenix are viable Rails alternatives for the right application. Check out the source code for Today I Learned, written in Elixir, and contact us if you need help with your Elixir project.