Molasses! A feature toggle library for Elixir

Early this year when I read about Erlang in Seven Languages In Seven Weeks, I mentioned that Elixir was a language I intended to explore this year. At Maxwell Health, we also started to investigate Elixir for new projects because we wanted a functional language in our arsenal and we liked it’s concurrency story. So I thought it would be in my best interest to dive into Elixir. I read through Programming Elixir and Programming Phoenix and recently started work on several Elixir projects.

Feature toggling is a way to release code to production without executing it by default. There are several ways to leverage feature toggles: releasing a feature production that may not be ready for customers or may be broken, releasing a feature to a subset of users or simply A/B testing. I wanted to create a library that captured all of these features for Elixir. Having contributed to other feature toggle libraries, I had a basic sense of the features I wanted. I wanted to be able to activate and deactivate features, have features that could be shown to a percentage of users and have features that could be only available to groups of users. In languages like PHP, this can mean several classes that are managing these pieces of functionality. However, in Elixir I could leverage pattern matching which shrank my code down.

 

    def is_active(client, key, id)  do
        case get_feature(client, key) do
            {:error, _} -> false
            %{active: false} -> false
            %{active: true,percentage: 100, users: []} -> true
            %{active: true,percentage: 100, users: users} -> Enum.member?(users, id)
            %{active: true,percentage: percentage} when is_integer(id) ->
                value = Integer.to_string(id) |> :erlang.crc32 |> rem(100) |> abs
                value <= percentage 
            %{active: true,percentage: percentage} when is_bitstring(id) ->
                value = id |> :erlang.crc32 |> rem(100) |> abs
                value <= percentage
        end
    end

The code above handles all of those features in just a few lines and it handles several kinds of Ids (strings and integers). Isn’t that cool? Other than pattern matching, other languages features I’ve enjoyed are the piping of functions into one another. It has been a great way to visualize how data is being manipulated in the pipeline. I can’t wait to explore more of Elixir in the new year.

You can check out the whole repo on Github.

 

Leave a Reply