diff --git a/lib/app.rb b/lib/app.rb index 466a789..180ff64 100644 --- a/lib/app.rb +++ b/lib/app.rb @@ -1,6 +1,7 @@ require_relative 'snapshot' require 'sinatra' require 'sinatra/jsonp' +require 'yajl' helpers do def base @@ -15,11 +16,13 @@ end get '/latest' do jsonp Snapshot .last - .to_base base + .with_base(base) + .to_hash end get '/:date' do |date| jsonp Snapshot .new(date) - .to_base base + .with_base(base) + .to_hash end diff --git a/lib/snapshot.rb b/lib/snapshot.rb index 50c0347..3a54c34 100644 --- a/lib/snapshot.rb +++ b/lib/snapshot.rb @@ -1,22 +1,25 @@ require_relative 'db' class Snapshot + DEFAULT_BASE = 'EUR' + def self.last new Currency.last_date end def initialize(date) @date = date + @base = DEFAULT_BASE end # Ugly as fuck. - def to_base(base) + def to_hash rebased_rates = rates - unless base == 'EUR' + unless @base == DEFAULT_BASE base_rate = rebased_rates .update('EUR' => 1.0) - .delete base + .delete @base rebased_rates.each do |iso_code, rate| new_rate = rate / base_rate @@ -33,12 +36,17 @@ class Snapshot end { - base: base, + base: @base, date: @date, rates: rebased_rates } end + def with_base(base) + @base = base + self + end + private def rates diff --git a/spec/app_spec.rb b/spec/app_spec.rb index e54cf33..e391fc5 100644 --- a/spec/app_spec.rb +++ b/spec/app_spec.rb @@ -1,6 +1,7 @@ require_relative 'helper' require 'rack/test' require 'app' +require 'yajl' describe 'the application' do include Rack::Test::Methods diff --git a/spec/rebasing_spec.rb b/spec/rebasing_spec.rb index 7e6b805..d83e639 100644 --- a/spec/rebasing_spec.rb +++ b/spec/rebasing_spec.rb @@ -2,28 +2,30 @@ require_relative 'helper' require 'snapshot' describe 'when rebased to a new base' do - let(:base) { 'USD' } + let(:new_base) { 'USD' } let(:snapshot) { Snapshot.new 'a date' } - let(:rates) { { 'USD' => 1.2781 } } - let(:rebased) do + let(:rates) { { new_base => 1.2781 } } + let(:rebased_hash) do snapshot.stub :rates, rates do - snapshot.to_base base + snapshot + .with_base(new_base) + .to_hash end end it 'resets base' do - rebased[:base].must_equal base + rebased_hash[:base].must_equal new_base end it 'adds former base to rates' do - rebased[:rates].keys.must_include 'EUR' + rebased_hash[:rates].keys.must_include Snapshot::DEFAULT_BASE end it 'removes new base from rates' do - rebased[:rates].keys.wont_include base + rebased_hash[:rates].keys.wont_include new_base end it 'rebases rates' do - rebased[:rates]['EUR'].must_equal 0.7824 + rebased_hash[:rates][Snapshot::DEFAULT_BASE].must_equal 0.7824 end end