I enjoy data manipulations. You have data coming in and data coming out, it is like kneading modeling clay to create something meaningful from a formless shape.
Let’s say our task at hand is to summarize data on daily basis from API endpoint that is providing list of activities and it may or may not have several activities during the day:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Let’s parse our JSON data and get array of activities
First manipulation of the data would be to transform it to format that we want to work with. By reading API docs we know that distance from given endpoint is provided in miles, calories is self explanatory, duration is provided in minutes and captured_at is a UNIX timestamp. As a European and a sane person, I want to convert miles to metric system and our internal app uses meters to represent distance. We care about time only in context of date so let’s convert it to Date object.
1 2 3 4 5 6 7 8
I use fetch here to get values from a hash, because that is sort of a test for making sure, that our assumption about the structure of the data is correct. If any of given keys are not present or 3rd party changes their API, we can find it out early.
Ok, so far, so good. Let’s get to the tricky part of summarizing the data. As a first step we need to group activities by date. That is pretty easy to do with Rubys group_by function. It will create a hash containg array of elements that match the condition provided in block as a value and and key as a condition itself.
Each element in groups_of_activities now represents all the data needed for single summary for day. We will iterate over groups of activities and we want to transform each of these groups to single summary.
We can take each activity group and map it. Inside the block we will calculate each value by by mapping the same group of primitives (Integers) of that value and reducing it by passing a function reference as a symbol, &:+ in our case.
1 2 3 4 5 6 7 8
Ad viola! We have a collection of activity summaries. Ill print summaries converted to JSON. Did that behind the scenes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Here is a full Gist of the code with simple spec