diff options
| author | Teddy Wing | 2018-03-15 17:09:49 +0100 |
|---|---|---|
| committer | Teddy Wing | 2018-03-15 17:44:22 +0100 |
| commit | 7fb536325c19e837d10707e9adfc0d8bce5a3976 (patch) | |
| tree | 1f9595434dd7b979c6e1f5bc659c177d1c1b1d15 | |
| parent | fa0fdbe92d441e1a226a56c792c014a032fd46e9 (diff) | |
| download | chouette-core-7fb536325c19e837d10707e9adfc0d8bce5a3976.tar.bz2 | |
Add `RouteWayCostJSONSerializer`
This serialiser will take `Route#costs` and convert the distance and
time fields from meters to kilometres and seconds to minutes
respectively. We need this because the frontend uses kilometre and
minute units while the TomTom API gives us the others (and we store the
data we get from TomTom without treatment).
Unfortunately, due to the way that Rabl works, this doesn't quite work
just yet. The serializer returns a string, and Rabl just puts this
string into the JSON output instead of a real JSON hash. Looks like I'm
going to have to convert my serializer into a generic converter.
Refs #6203
| -rw-r--r-- | app/views/routes/costs.rabl | 4 | ||||
| -rw-r--r-- | lib/route_way_cost_json_serializer.rb | 22 | ||||
| -rw-r--r-- | spec/lib/route_way_cost_json_serializer_spec.rb | 31 |
3 files changed, 56 insertions, 1 deletions
diff --git a/app/views/routes/costs.rabl b/app/views/routes/costs.rabl index d4465d03e..2c336fb51 100644 --- a/app/views/routes/costs.rabl +++ b/app/views/routes/costs.rabl @@ -1,2 +1,4 @@ object @route -attributes :costs +node :costs do + RouteWayCostJSONSerializer.dump(@route.costs) +end diff --git a/lib/route_way_cost_json_serializer.rb b/lib/route_way_cost_json_serializer.rb new file mode 100644 index 000000000..20b3d6ee2 --- /dev/null +++ b/lib/route_way_cost_json_serializer.rb @@ -0,0 +1,22 @@ +class RouteWayCostJSONSerializer + def self.dump(way_costs) + return if way_costs.nil? + + way_costs.each do |_, costs| + costs['distance'] = self.meters_to_kilometers(costs['distance']) + costs['time'] = self.seconds_to_minutes(costs['time']) + end + + JSON.dump(way_costs) + end + + private + + def self.meters_to_kilometers(num) + num / 1000.0 + end + + def self.seconds_to_minutes(num) + num / 60 + end +end diff --git a/spec/lib/route_way_cost_json_serializer_spec.rb b/spec/lib/route_way_cost_json_serializer_spec.rb new file mode 100644 index 000000000..52cb21afc --- /dev/null +++ b/spec/lib/route_way_cost_json_serializer_spec.rb @@ -0,0 +1,31 @@ +RSpec.describe RouteWayCostJSONSerializer do + describe ".dump" do + it "converts distance from meters to km and time from seconds to minutes" do + costs = { + '1-2': { + 'distance' => 35223, + 'time' => 5604 + }, + '94435-97513' => { + 'distance' => 35919, + 'time' => 6174 + } + } + + expect( + RouteWayCostJSONSerializer.dump(costs) + ).to eq(<<-JSON.delete(" \n")) + { + "1-2": { + "distance": 35.223, + "time": 93 + }, + "94435-97513": { + "distance": 35.919, + "time": 102 + } + } + JSON + end + end +end |
