From 48c5579974f89451e307c986fdd1d161d21790f4 Mon Sep 17 00:00:00 2001 From: Georg Gadinger Date: Fri, 26 Jan 2018 20:02:26 +0100 Subject: [PATCH] Sort rates by the currency ISO code --- app/lib/quote.rb | 9 ++++----- app/spec/quote_spec.rb | 6 ++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/app/lib/quote.rb b/app/lib/quote.rb index a0aad94..fc7e863 100644 --- a/app/lib/quote.rb +++ b/app/lib/quote.rb @@ -58,7 +58,7 @@ class Quote end def find_default_rates - Currency.where(date: date).reduce({}) do |rates, currency| + Currency.where(date: date).order(:iso_code).reduce({}) do |rates, currency| rates.update(Hash[currency.to_h.map { |k, v| [k, round_rate(v * amount)] }]) end end @@ -67,11 +67,10 @@ class Quote rates = find_default_rates denominator = rates.update(DEFAULT_BASE => amount).delete(base) raise Invalid, 'Invalid base' unless denominator - rates.each do |iso_code, rate| - rates[iso_code] = round_rate(amount * rate / denominator) - end - rates + .map { |(iso_code, rate)| [iso_code, round_rate(amount * rate / denominator)] } + .sort_by(&:first) + .to_h end # I'm mimicking the apparent convention of the ECB here. diff --git a/app/spec/quote_spec.rb b/app/spec/quote_spec.rb index 110badb..7e80d8e 100644 --- a/app/spec/quote_spec.rb +++ b/app/spec/quote_spec.rb @@ -56,6 +56,12 @@ describe Quote do rate.must_equal 1.4296 end end + + it 'returns the currencies sorted' do + stub_rates 'BAZ' => 1.5, 'FOO' => 2, 'BAR' => 3, 'QUX' => 4 do |quote| + quote.rates.keys.must_equal quote.rates.keys.sort + end + end end describe 'when given an invalid base' do