aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTeddy Wing2018-03-13 12:04:19 +0100
committerTeddy Wing2018-03-14 16:38:40 +0100
commit11894d94b6698590a9ddb37729fdd90ea081159d (patch)
tree513946bd479fcbf88d0d32ab9f39a4d1853a4070
parent87947a7b6da52305029954341c6dc40b8cde6f86 (diff)
downloadchouette-core-11894d94b6698590a9ddb37729fdd90ea081159d.tar.bz2
Add `WayCostCollectionJSONSerializer`
A JSON serialiser for a collection of `WayCost`s. This will be used to store `WayCost`s for a `Chouette::Route` in the `Route#costs` JSON field. Refs #6095
-rw-r--r--lib/way_cost_collection_json_serializer.rb16
-rw-r--r--spec/lib/way_cost_collection_json_serializer_spec.rb37
2 files changed, 53 insertions, 0 deletions
diff --git a/lib/way_cost_collection_json_serializer.rb b/lib/way_cost_collection_json_serializer.rb
new file mode 100644
index 000000000..191871cca
--- /dev/null
+++ b/lib/way_cost_collection_json_serializer.rb
@@ -0,0 +1,16 @@
+class WayCostCollectionJSONSerializer
+ def self.dump(way_costs)
+ return if way_costs.nil?
+
+ costs_by_id = {}
+
+ way_costs.each do |way_cost|
+ costs_by_id[way_cost.id] = {
+ distance: way_cost.distance,
+ time: way_cost.time
+ }
+ end
+
+ JSON.dump(costs_by_id)
+ end
+end
diff --git a/spec/lib/way_cost_collection_json_serializer_spec.rb b/spec/lib/way_cost_collection_json_serializer_spec.rb
new file mode 100644
index 000000000..22faf88d3
--- /dev/null
+++ b/spec/lib/way_cost_collection_json_serializer_spec.rb
@@ -0,0 +1,37 @@
+RSpec.describe WayCostCollectionJSONSerializer do
+ describe ".dump" do
+ it "creates a JSON hash of hashed WayCost attributes" do
+ way_costs = [
+ WayCost.new(
+ departure: Geokit::LatLng.new(48.85086, 2.36143),
+ arrival: Geokit::LatLng.new(47.91231, 1.87606),
+ distance: 1234,
+ time: 99,
+ id: '1-2'
+ ),
+ WayCost.new(
+ departure: Geokit::LatLng.new(47.91231, 1.87606),
+ arrival: Geokit::LatLng.new(52.50867, 13.42879),
+ distance: 5678,
+ time: 999,
+ id: '2-3'
+ )
+ ]
+
+ expect(
+ WayCostCollectionJSONSerializer.dump(way_costs)
+ ).to eq(<<-JSON.delete(" \n"))
+ {
+ "1-2": {
+ "distance": 1234,
+ "time": 99
+ },
+ "2-3": {
+ "distance": 5678,
+ "time": 999
+ }
+ }
+ JSON
+ end
+ end
+end