Plataformatec Blog Plataformatec's place to talk about Ruby, Ruby on Rails and software engineering Wed, 12 Nov 2014 11:00:42 +0000 en-US hourly 1 Converting Erlang code into Elixir Wed, 12 Nov 2014 11:00:42 +0000 »]]> When you are new to any language, you probably want to run some existing code just to see how it works. Achieving success while trying new things is important, because it helps fueling your interest.

The number of code examples in Elixir is increasing, but sometimes you will have to read some Erlang code. Recently, I wanted to play a little bit with Cowboy HTTP Server, which is written in Erlang. The Cowboy repo has a lot of small examples presenting the features which is provided by it. When I tried to convert one of them to Elixir, it wasn’t as simple as I expected, since I’m not so familiarized with the language yet.

When converting, you may get into some misleading code that will not work as you expected at first. So, I’m going to present a transcoding of Cowboy WebSocket server example from Erlang to Elixir, so that you can learn some of the details that exists in the process of porting Erlang code into Elixir code.

This will not be a tutorial explaining how that Cowboy example works, it’s just about how to convert it to Elixir. Also, I’m not going to show how it could be done in idiomatic Elixir, the goal here is to translate Erlang code into Elixir the simplest way possible.

So let’s start!

Creating the project

Create a project called ws_cowboy with the following command:

mix new ws_cowboy
cd ws_cowboy

After that we are going to change/create 4 files:

  • mix.exs: declares the dependencies in the project and the application module to run
  • lib/ws_cowboy.ex: the application module that setups the cowboy routes and http server
  • lib/ws_handler.ex: handles a WebSocket request connection
  • lib/ws_supervisor.ex: supervisor for Cowboy server

Also, copy the whole priv directory from the Cowboy example to the project’s root dir.

The project definition

In the mix.exs file we are going to add the Cowboy dependency and also configure the module application, in this case WsCowboy.

defmodule WsCowboy.Mixfile do
  use Mix.Project

  def project do
    [app: :ws_cowboy,
     version: "0.0.1",
     elixir: "~> 1.0",
     deps: deps]

  # Configuration for the OTP application
  # Type `mix help` for more information
  def application do
    [applications: [:logger, :cowboy],
     mod: {WsCowboy, []}]

  # Dependencies can be Hex packages:
  #   {:mydep, "~> 0.3.0"}
  # Or git/path repositories:
  #   {:mydep, git: "", tag: "0.1.0"}
  # Type `mix help deps` for more examples and options
  defp deps do
    [{:cowboy, "~> 1.0.0"}]

Configuring the HTTP application

Here is the transcode of websocket_app.erl file to the ws_cowboy.ex file:

defmodule WsCowboy do
  @behaviour :application

  def start(_type, _args) do
    dispatch = :cowboy_router.compile([
      {:_, [
        {"/", :cowboy_static, {:priv_file, :ws_cowboy, "index.html"}},
        {"/websocket", WsHandler, []},
        {"/static/[...]", :cowboy_static, {:priv_dir, :ws_cowboy, "static"}}
    {:ok, _} = :cowboy.start_http(:http, 100, [{:port, 8080}],
                                  [{:env, [{:dispatch, dispatch}]}])

  def stop(_state) do

If you never read any Erlang code and you came from a language like Ruby, you might get confused on basic things. So, let’s go through some of the details of porting websocket_app.erl to the ws_cowboy.ex.

Erlang files represents a module, in Elixir it is the same thing, but in this case we use the defmodule macro. Erlang modules can be accessed using :<module_name>, so in this case we are defining that this module has the application behaviour.

Different from other languages like Ruby, lowercase names aren’t variables in Erlang, but atoms, while in Elixir atoms look the same as Ruby symbols. So, we scanned every lowercase names and replaced them with :<name>.

Upper case names in Erlang aren’t constant but variables, so we changed them to lowercase. It is good to do this in inverse order to avoid mixing variables and atoms.

During the process of converting this file, there was a line making the application not work and I spent some time trying to figure out what was wrong. In Ruby, 'foo' and "foo" are both strings, but in Elixir and Erlang they are different things. The single quote in Erlang is an atom (symbol), so the '_' line must be converted to :_ in Elixir. If you miss this little detail, unfortunately it will compile and run, but Cowboy will always return a 400 status code.

Except that, everything is pretty straightforward, the only detail is the :cowboy_static definition that you have to replace with your dir app name, in this case :ws_cowboy.

To transcode function calls, you just have to replace the : with ., like in Ruby.

Handling the WebSocket connection

You can read more about how Cowboy handles WebSocket here. Here’s the transcode of the file ws_handler.erl to ws_handler.ex:

defmodule WsHandler do
  @behaviour :cowboy_websocket_handler

  def init({:tcp, :http}, _req, _opts) do
    {:upgrade, :protocol, :cowboy_websocket}

  def websocket_init(_transport_name, req, _opts) do
    :erlang.start_timer(1000, self(), "Hello!")
    {:ok, req, :undefined_state}

  def websocket_handle({:text, msg}, req, state) do
    {:reply, {:text, "That's what she said! #{msg}"}, req, state}

  def websocket_handle(_data, req, state) do
    {:ok, req, state}

  def websocket_info({:timeout, _ref, msg}, req, state) do
    :erlang.start_timer(1000, self(), "How' you doin'?")
    {:reply, {:text, msg}, req, state}

  def websocket_info(_info, req, state) do
    {:ok, req, state}

  def websocket_terminate(_reason, _req, _state) do

Following the steps done in the previous file, there is no secret on this one. The only detail is that the Erlang version used binary notation for strings, but in Elixir you can use just "string" normally. Also, you can use string interpolation "That's what she said! #{msg}".

Writing the supervisor

Now there’s just one translation missing, from websocket_sup.erl to ws_supervisor.ex. Here we just used __MODULE__ instead of the Erlang ?MODULE:

defmodule WsSupervisor do
  @behaviour :supervisor

  def start_link do
    :supervisor.start_link({:local, __MODULE__}, __MODULE__, [])

  def init([]) do
    procs = []
    {:ok, {{:one_for_one, 10, 10}, procs}}

Running your server

Running your server is pretty easy, just run the mix run --no-halt command and check in your browser.


The goal of this post was to show an example of how to port Erlang code into Elixir code. The result we got is the simplest translation possible, it was not my idea to write idiomatic Elixir here. For example, in Elixir you would not use Erlang’s supervisor module, but rather the Elixir’s supervisor.

I hope you could get the picture of how it is to translate Erlang code into Elixir, how it’s not so hard and some of the details that you must pay attention while doing it.

If you are interesting in learning more about Elixir, check out the getting started page.

Do you had any issues when starting to play with Elixir that you cracked your head to figuring out why it didn’t work? Share your experience and doubts with us!

]]> 0
How to serialize Date and DateTime to JSON without losing information Wed, 05 Nov 2014 11:00:36 +0000 »]]> When building APIs, it is pretty common to use JSON as a serialization format. JSON defines serialization for boolean, number and string, but not for date/datetime values.

What most serializers do with Date and DateTime values is to use the ISO8601 standard. For example:

# Date format

# DateTime format

However, you should be aware that information is lost when you use the Date format. That happens because a Date value might differ between different timezones. Let me give you an example:

  • a request was issued at 2011-07-14 T01:00:00Z (UTC) from Brazil (UTC-0300) to a service in UTC
  • if the time the request was created is exposed as a Date, it would return the value as 2011-07-14
  • but from the client’s perspective in Brazil, the correct date is 2011-07-13, since at the moment of that request was issued, the local time in Brazil was 2011-07-13 T22:00:00-0300

If this information is used only inside your app, within the same timezone, you would have no problems. But, if you need to make this information available through a public API, one of your API’s consumers might recover an incorrect value.

So, from this experience, any date value that will be shared and consumed by different clients should be represented as date time with explicit timezone or using the Unix time format. That way, it is up to the client to treat the data properly.

Here is an example of an API that returns a subscription period in the right way:

  period_start_date: 1409175049, # Unix time
  period_end_date: 2014-09-27T18:30:49-0300 # ISO8601

# DateTime.parse(“2014-09-27T18:30:49-0300”)

The options above have the advantage that both are unambiguous and sortable. You may choose between one or another based on the fact that the timezone option is easier for human comprehension. But remember that Timezones are a presentation-layer problem, so if you just need to pass data around, Unix time is preferable.

Have you ever had this serialization problem or any other that caused information to be lost? If you have questions or any experience to share, please, leave a comment below.

]]> 4
Playing with Elixir and Go concurrency models Wed, 29 Oct 2014 11:00:19 +0000 »]]> In Go Concurrency Patterns talk, Google I/O 2012, presenter Rob Pike demos some great concurrency features from Go, like channels and Go routines, and how it can be used to build fast, replicated and robust software.

Concurrency patterns is a very interesting topic but there was one statement in special that got me thinking:

“The models are equivalent but express things differently.”

This is about the distinction between Go channels and its cousin Erlang messages passing approach to communicating between processes.

Implementing Go channels with Elixir processes and messages

Before discovering that it has been done before, I wrote some simple Elixir code to play with the theoretical equivalence between those two models.

Notice that this implementation is not meant to be complete, nor efficient and is not recommended for production software. Don’t do it at home.

defmodule GoChannel do
  def make do

  def write(channel, val) do
    send(channel, { :write, val})

  def read(channel) do
    send(channel, { :read, self })

    receive do
      { :read, channel, val} -> val

  def loop do
    receive do
      { :read, caller } -> receive do
        { :write, val } -> send(caller, { :read, self, val }); loop

Some tests

defmodule GoChannelTest do
  use ExUnit.Case

  test "write and read to a channel" do
    channel = GoChannel.make
    GoChannel.write(channel, 'hello')
    assert == 'hello'

  test "write and read preserves order" do
    channel = GoChannel.make
    GoChannel.write(channel, 'hello')
    GoChannel.write(channel, 'world')
    assert == 'hello'
    assert == 'world'

This pseudo channel implementation relies on a combination of messages between processes to simulate the original FIFO behaviour of channels.

The same way one could pass a channel as parameter to other functions, since it’s a first-class citizen, we could pass the result of GoChannel.make, since it’s a PID, which in turn is a first-class citizen in Elixir.

Back to concurrency patterns

The first pattern demonstrated in Rob’s talk was fanIn, where two channels were combined into a single one.

func fanIn(input1, input2 <-chan string) <-chan string {
    c := make(chan string)
    go func() { for { c <- <-input1 } }()
    go func() { for { c <- <-input2 } }()
    return c

We could translate this code to Elixir, using our borrowed abstraction:

defmodule Patterns do
  def fan_in(chan1, chan2) do
    c = GoChannel.make

    spawn(loop(fn -> GoChannel.write(c, end))
    spawn(loop(fn -> GoChannel.write(c, end))


  defp loop(task) do
    fn -> task.(); loop(task) end

Some tests:

defmodule PatternsTest do
  use ExUnit.Case

  test "fan_in combines two channels into a single one" do
    chan1 = GoChannel.make
    chan2 = GoChannel.make

    c = Patterns.fan_in(chan1, chan2)

    GoChannel.write(chan1, 'hello')
    GoChannel.write(chan2, 'world')

    assert == 'hello'
    assert == 'world'

We could go even further in this mimic game and try to implement the select statement, but that would be a very extensive one. First let’s reflect a little about composing more complex functionality with channels.

Channels as Streams

From a consumers perspective, reading from a channel is like getting values out of a stream. So, one could wrap a channel in a stream, using the Stream.unfold/2 function:

  def stream(channel) do
                  fn channel -> {read(channel), channel} end)

This function returns a Stream, which gives us lots of power to compose using its module functions like map/2, zip/2, filter/2, and so on.

One test to demo that:

  test "compose channel values with streams" do
    channel = GoChannel.make
    stream =

    GoChannel.write(channel, 1)
    GoChannel.write(channel, 2)
    GoChannel.write(channel, 3)

    doubles =, &(&1 * 2)) |> Stream.take(2) |> Enum.to_list

    assert doubles == [2, 4]

Reviewing comparisons

The following quote from Rob Pike's talk is one common analogy used to compare channels and Erlang concurrency models:

“Rough analogy: writing to a file by name (process, Erlang) vs. writing to a file descriptor (channel, Go).”

I think analogies are really useful for communication but I believe they work better as the start of an explanation, not its summarization. So I think we could detail differences a little further.

For example, PIDs are not like “file names” since they are anonymous and automatically generated. As we just saw, PID is a first-class citizen and in the language’s perspective, is just as flexible as a channel.

I would say that channels abstraction reinforce isolation from producer to consumer, in the sense that Go routines writing to a channel doesn't know when nor who is going to consume that information. But it doesn't mean that using processes and messages one could not achieve the same level of isolation, as we just demoed.

On the other hand, identifying producers and consumers explicitly allow us to monitor and supervise them, allowing language like Erlang and Elixir to leverage the so-called supervision trees useful for building fault-tolerant software in those languages.

Besides been an interesting exercise to mimic Go’s way of solving problems, one should be aware that Erlang and Elixir have their own abstractions and patterns for handling concurrency.
For example, one could use the GenEvent module to implement a pub/sub functionality.

Elixir, Erlang and Go have some common goals, like the ones cited in the first paragraph of this post, but they also have their specifics. Embracing differences provides better results in the long term because it helps leverage each language power.


]]> 0
Estamos contratando mais desenvolvedores! Wed, 22 Oct 2014 11:00:38 +0000 »]]>  

Plataformatec team

Neste ano a Plataformatec completou apenas 5 anos, mas olhando para tudo que nós conseguimos conquistar, parece que se passou muito mais tempo. É fato que nós cometemos alguns erros, mas é uma enorme certeza de que aprendemos muito mais.

E agora, que nós estamos olhando para os próximos anos, queremos convidar mais pessoas a juntarem-se ao nosso time. Nós queremos pessoas que compartilhem dos nossos valores, que se importem com o que fazem e que não cansem de aprender e de se superarem.

Se você está interessado em trabalhar em um ambiente que exige colaboração e que estimula as pessoas a se desenvolverem, então queremos te convidar para participar do nosso processo seletivo.

Estamos contratando mais desenvolvedores e os requisitos da vaga são:

  • Inglês intermediário
  • Experiência com desenvolvimento de aplicativos web em qualquer linguagem (pelo menos 1 ano)
  • Experiência com Ruby e Rails (pelo menos 6 meses)
  • Disponibilidade integral
  • Local: São Paulo (nosso escritório)

Para participar do processo seletivo visite Veja também nossa página no Facebook para conhecer mais sobre o nosso time.

Estamos esperando por você!

]]> 0
The brand new Plataformatec blog Tue, 30 Sep 2014 12:00:35 +0000 »]]> Today we are shipping a whole new design to improve your navigation and reading experience on our blog!

The brand new Plataformatec blog

Back in 2012 we rolled out our new visual identity and website, but we didn’t change our blog much at the time. So we decided that it was time to give some love to our blog and work on a full redesign over the last couple of months. We are really excited to release this work for everybody who reads our posts.

Fonts are bigger, colors are brighter and everything looks much better on your smartphone than it used to. We focused on improving the reading experience and on a more up to date look for our blog.

The whole development process was a great experience, from design to code, and I want to share some of the story of how we got there:

The (re)design process

At first we started sketching everything with HTML and CSS trying to put together our new look with some elements of our existing layout. As things started coming into shape, the next step was to put together a Jekyll website with all of our blog posts (thanks to jekyll-import) so we could easily test the new design against our existing content, rather than against a bunch of “Lorem ipsum” posts. This was really useful when reviewing the code snippets in our posts and visualizing how we could improve the syntax highlight using something else than the previous WordPress plugin we were using.

As we designed and prototyped each piece of our new layout, people outside the redesign project jumped in and participated through the Pull Requests that we used for building those blocks. A good part of our team was part of the whole process helping out with design/code/copy feedback.

One of the Pull Requests in our new theme

The Journey into WordPress

One of the first decisions was to keep using WordPress as our blog engine. Over the last years a lot of alternatives have surfaced (like Ghost), but WordPress still feels the most complete blogging solution for us, so we’re still using it for the time being.

Given that, one of our challenges was to learn how to work with WordPress and convert our design (built on top of a Jekyll site) into a WordPress theme that we could install in our blog. This task ended up being much easier than expected.

After finishing the first complete iteration of the layout, I spent a few days watching some of the WordPress courses on Treehouse to learn how to work with WordPress themes and the whole PHP API behind it. I’ve mixed together some Bash scripts, a proxy server built with rack-legacy and some Gulp tasks to automate a local WordPress environment and migrated our Jekyll templates into PHP ones and we were set!

This might sound a bit too complicated, but the idea of starting with Jekyll to focus on the design process and quick iterations to later worry about the theme “infrastructure” was a well payed bet so I didn’t have to juggle both problems at the same time.

The best is yet to come

The idea is to not stop here. There are still a lot of improvements we want to do on our blog and all the tooling we have put together makes it easy to jump back and iterate over the design and the code.

Let us know if you find anything broken around here and we will jump on it to fix it. We hope you enjoy this new look and feel while reading through our blog posts :heart:!

]]> 3
Writing assertive code with Elixir Wed, 24 Sep 2014 12:00:01 +0000 »]]> Functional languages are typically great languages for writing assertive code and Elixir is no exception. In this blog post, I would like to discuss some anti-patterns I have seen in Elixir code and how to rewrite them in a way to make the best of Elixir.

Pattern matching

Imagine you have a string with format foo=bar&token=value&bar=baz where you want to extract the value for the key token which may appear anywhere or not at all in the string.

Here is one solution a developer not very-acquainted with pattern matching would try:

def get_token(string) do
  parts = String.split(string, "&")
  Enum.find_value(parts, fn pair ->
    key_value = String.split(pair, "="), 0) == "token" &&, 1)

At first the code seems to work fine but once we go deeper we can see it makes many assumptions we have not really planned for!

For example, what happens if someone passes "foo=bar&token=some=value&bar=baz" as argument? The code will work and will return the string "some". But is that what we really want? Maybe we wanted "some=value" instead? Or maybe we wanted to reject it all together?

There are other examples where the code above would work by accident, possibly adding complexity to the codebase as other users may start to rely on such behaviour.

The most idiomatic way of writing the code above in Elixir is by using pattern matching:

def get_token(string) do
  parts = String.split(string, "&")
  Enum.find_value(parts, fn pair ->
    [key, value] = String.split(pair, "=")
    key == "token" && value

With pattern matching, we are asserting that String.split/2 is going to return a list with two elements. If someone passes "foo=bar&token&bar=baz", it will crash as the list will have only one element. If someone passes "token=some=value", it will crash too as it contains 3 items.

Our new code does not contain any of the accidental complexity of the previous one and it will also be faster. Any input that does not match the given pattern will lead to a crash, giving us the perfect opportunity to discuss and decide how to handle those corner cases.

Polymorphism is opt-in

Elixir provides protocols as a mechanism for polymorphism. A protocol allows developers to express they are willing to work with any data type, as long as it implements the protocols X, Y and Z.

I have previously compared Elixir protocols to alternatives in languages like Swift and Ruby. One nice aspect of Elixir protocols is that they are explicit, you need to explicitly outline and define a protocol for data structures to implement.

For example, one protocol in Elixir is the String.Chars protocol, which converts any data type to a string, if that data type can be converted to a human-readable string. The to_string function uses such protocol for conversions:

iex> to_string("hello")
iex> to_string(1)
iex> to_string URI.parse("")
iex> to_string %{hello: :world}
** (Protocol.UndefinedError) protocol String.Chars not implemented for %{hello: :world}

Imagine you have a function that converts underscores to dashes in a string:

def dasherize(string), do: String.replace(string, "_", "-")

Now imagine that at some point you decide to call to_string/1 before calling replace/3:

def dasherize(data), do: String.replace(to_string(data), "_", "-")

Albeit small, this is a drastic change to our code. Our dasherize function went from supporting only strings as argument to support a large number of data types. In other words, our code became less assertive and more generic.

That said, before adding protocols to our code, we should ask if we really intend to open our function to all types. Maybe we want dasherize to support only atoms and strings? If so, we should rather write:

def dasherize(data) when is_atom(data), do: dasherize(Atom.to_string(data))
def dasherize(data), do: String.replace(data, "_", "-")

However, if we are confident we want a protocol, then we should indeed use the protocol and write a test case that guarantees our function works for at least a couple types that implement such protocol. Such tests are extremely important to guarantee we don’t make a different assumption somewhere in the same function.

Note this trade-off does not only happen in protocols, but in any polymorphic API, like the Dict module. In practice, one should rather use specific dict implementations, like the Keyword and Map modules, and rely on the Dict module only when polymorphism is desired.

Map/struct access

Elixir provides maps, known as dictionaries in other languages, as a key-value data structure. Maps are created as follows:

map = %{name: "john", age: 42}

Maps allow two types of access. A strict access, that requires the field name to exist in the map, and a dynamic access, that returns nil if the field does not exist in the map:

# Strict access
iex> map.address
** (KeyError) key :address not found in: %{age: 42, name: "john"}

# Dynamic access
iex> map[:name]
iex> map[:address]

Both syntaxes have their use cases but we should prefer the strict syntax when possible as it helps us find bugs early on. The same applies to structs, which are named maps:

defmodule User do
  defstruct [:first_name, :last_name, :age]

  def name(user) do
    "#{user.first_name} #{user.last_name}"
end %User{first_name: "John", last_name: "Doe"}
#=> "John Doe"

In the example above, we have defined a User struct and a name/1 function that receives the struct and returns its name. Since we are using user.first_name, if we accidentally pass a struct that does not contain such a field, it will crash immediately, with a nice error message!

In fact, the strict aspect of the user.first_name syntax is one of the reasons why structs do not support the dynamic syntax out of the box:

user = %User{first_name: "John", last_name: "Doe"}
** (Protocol.UndefinedError) protocol Access not implemented for %User{...}

In case you want to use the dynamic syntax, you need to derive the Access protocol for the User struct:

defmodule User do
  @derive [Access]
  defstruct [:first_name, :last_name, :age]

  def name(user) do
    "#{user.first_name} #{user.last_name}"

However, only derive Access when you truly need to do so, as it is much better to push yourself to rely more on the strict syntax. I would even say relying on Access for structured data is an anti-pattern itself!

Wrapping up

The most interesting aspect of all examples above is that writing in the assertive style leads to faster, more concise and maintainable code. Even more, it allows us to focus on specific scenarios, postponing any complexity (incidental or accidental) to only when we need them, if we need them.

]]> 0