Created
February 15, 2014 19:06
-
-
Save janjiss/9023711 to your computer and use it in GitHub Desktop.
Example 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "json" | |
| require "rspec" | |
| json_data = <<-JSON | |
| {"activities": [ | |
| { | |
| "captured_at": 1392366463, | |
| "distance": "1.12", | |
| "duration": 12, | |
| "calories": 100 | |
| }, | |
| { | |
| "captured_at": 1392355727, | |
| "distance": "4.20", | |
| "duration": 80, | |
| "calories": 400 | |
| }, | |
| { | |
| "captured_at": 1392280163, | |
| "distance": "2.32", | |
| "duration": 20, | |
| "calories": 2200 | |
| } | |
| ]} | |
| JSON | |
| def miles_to_meters(miles) | |
| (miles.to_f/0.00062137).to_i | |
| end | |
| activity_data = JSON.parse(json_data).fetch('activities') | |
| activity_data.map! do |a| | |
| a["distance"] = miles_to_meters(a.fetch("distance")) | |
| a["calories"] = a.fetch("calories").to_i | |
| a["duration"] = a.fetch("duration").to_i | |
| a["captured_at"] = Time.at(a.fetch("captured_at")).to_date | |
| a | |
| end | |
| groups_of_activities = activity_data.group_by {|a| a["captured_at"]} | |
| summaries = groups_of_activities.map do |date, activity_group| | |
| activity_group.reduce do |memo, obj| | |
| memo["distance"] += obj["distance"] | |
| memo["duration"] += obj["duration"] | |
| memo["calories"] += obj["calories"] | |
| memo["date"] = memo["captured_at"] | |
| memo | |
| end | |
| end | |
| summary = summaries.first | |
| describe "Summary" do | |
| it "summarizes distance" do | |
| expect(summary["distance"]).to eq(8561) | |
| expect(summary["duration"]).to eq(92) | |
| expect(summary["calories"]).to eq(500) | |
| expect(summary["date"]).to eq(Date.parse("2014-02-14")) | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment