Tel: (+44) 1482 234021 | info@wearesauce.io

A quick guide to the pipeline operator

We've been introducing a few developers to Elixir recently, who haven't seen the pipeline operator before. We figured it might be useful to point them to a blog post.

If you've not seen it before, here's an example below

LocationUpdateEvent
|> LocationQueries.filter_by_absolute_date_range(criteria.absolute_date_range_start, criteria.absolute_date_range_end)
|> LocationQueries.filter_by_relative_date_range(criteria.relative_date_range_days)
|> LocationQueries.filter_by_geozone(criteria.geozone_id)
|> LocationQueries.filter_by_day_of_week(criteria.day_of_week)
|> Repo.all

The code above is a composition of SQL queries for our LocationUpdateEvent model.

The pipeline operator basically takes the result of the previous line and drops it in as a the first arguement for the current line function.

Without the pipeline operator, the above code could be written something like this

location_update_event_query = LocationQueries.filter_by_absolute_date_range(LocationUpdateEvent, criteria.absolute_date_range_start, criteria.absolute_date_range_end)
location_update_event_query = LocationQueries.filter_by_relative_date_range(location_update_event_query, criteria.relative_date_range_days)
location_update_event_query = LocationQueries.filter_by_geozone(location_event_query, criteria.geozone_id)
location_update_event_query = LocationQueries.filter_by_day_of_week(location_event_query, criteria.day_of_week)
Repo.all(location_event_query)

Yep, quite a bit of extra typing and noise there.