diff --git a/lib/snapshot.rb b/lib/snapshot.rb index e84748a..bc24c3a 100644 --- a/lib/snapshot.rb +++ b/lib/snapshot.rb @@ -1,5 +1,4 @@ require_relative 'db' -require 'yajl' class Snapshot def self.last @@ -11,10 +10,31 @@ class Snapshot end def to_base(base) + rebased_rates = rates + + unless base == 'EUR' + base_rate = rebased_rates + .update('EUR' => 1.0) + .delete base + + rebased_rates.each do |iso_code, rate| + new_rate = rate / base_rate + rebased_rates[iso_code] = + case new_rate + when new_rate > 100 + new_rate.round 2 + when new_rate > 10 + new_rate.round 3 + else + new_rate.round 4 + end + end + end + { base: base, date: @date, - rates: rates + rates: rebased_rates } end diff --git a/spec/rebasing_spec.rb b/spec/rebasing_spec.rb new file mode 100644 index 0000000..7e6b805 --- /dev/null +++ b/spec/rebasing_spec.rb @@ -0,0 +1,29 @@ +require_relative 'helper' +require 'snapshot' + +describe 'when rebased to a new base' do + let(:base) { 'USD' } + let(:snapshot) { Snapshot.new 'a date' } + let(:rates) { { 'USD' => 1.2781 } } + let(:rebased) do + snapshot.stub :rates, rates do + snapshot.to_base base + end + end + + it 'resets base' do + rebased[:base].must_equal base + end + + it 'adds former base to rates' do + rebased[:rates].keys.must_include 'EUR' + end + + it 'removes new base from rates' do + rebased[:rates].keys.wont_include base + end + + it 'rebases rates' do + rebased[:rates]['EUR'].must_equal 0.7824 + end +end