Refactor rebasing

This commit is contained in:
Hakan Ensari 2012-11-21 12:44:33 +00:00
parent 462a87a876
commit 19b7a37563
4 changed files with 28 additions and 14 deletions

View File

@ -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

View File

@ -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

View File

@ -1,6 +1,7 @@
require_relative 'helper'
require 'rack/test'
require 'app'
require 'yajl'
describe 'the application' do
include Rack::Test::Methods

View File

@ -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