Refactor Currency

This commit is contained in:
Hakan Ensari 2015-08-30 10:36:32 +01:00
parent 214e8a8a1a
commit b95a2c5ee6
6 changed files with 61 additions and 9 deletions

View File

@ -16,6 +16,7 @@ gem 'yajl-ruby'
group :development do
gem 'minitest'
gem 'minitest-around'
gem 'rack-test'
gem 'shotgun'
end

View File

@ -18,6 +18,8 @@ GEM
method_source (0.8.2)
mini_portile (0.6.2)
minitest (5.6.1)
minitest-around (0.3.2)
minitest (~> 5.0)
multi_json (1.11.0)
newrelic_rpm (3.12.0.288)
nokogiri (1.6.6.2)
@ -70,11 +72,11 @@ PLATFORMS
DEPENDENCIES
fixer
minitest
minitest-around
newrelic_rpm
pry
rack-test
rake
rollbar
sequel_pg
shotgun
sinatra-cross_origin
@ -82,3 +84,6 @@ DEPENDENCIES
unicorn
virtus
yajl-ruby
BUNDLED WITH
1.10.6

View File

@ -1,7 +1,21 @@
# Wraps persisted currency data
class Currency < Sequel::Model
def self.last_date
order(:date).last.date
dataset_module do
def recent
order(Sequel.desc(:date))
end
def before(value)
where { date <= value }
end
def current_date
currency = recent.first
currency.date if currency
end
def current_date_before(value)
before(value).current_date
end
end
def to_hash

View File

@ -6,16 +6,14 @@ class Snapshot
include Virtus.model
attribute :base, String, default: 'EUR'
attribute :date, Date
attribute :date, Date, default: Currency.current_date
def quote
self.date =
if date
last_date = Currency.where("date <= '#{date}'").order(:date).last
last_date = Currency.current_date_before(date)
fail ArgumentError, 'Date too old' unless last_date
last_date.date
else
Currency.last_date
last_date
end
attributes.merge(rates: rebase(rates))

33
spec/currency_spec.rb Normal file
View File

@ -0,0 +1,33 @@
require_relative 'helper'
require 'currency'
describe Currency do
around do |test|
Currency.db.transaction do
test.call
raise Sequel::Rollback
end
end
before do
Currency.dataset.delete
@first = Currency.create(date: '2014-01-01')
@last = Currency.create(date: '2015-01-01')
end
it 'returns current date' do
Currency.current_date.must_equal @last.date
end
it 'returns current date before given date' do
Currency.current_date_before(@last.date - 1).must_equal @first.date
end
it 'returns nil if there is no current date before given date' do
Currency.current_date_before(@first.date - 1).must_be_nil
end
it 'casts to hash' do
@first.to_hash.must_be_kind_of Hash
end
end

View File

@ -2,3 +2,4 @@ ENV['RACK_ENV'] = 'test'
require './config/environment'
require 'minitest/autorun'
require 'minitest/pride'
require 'minitest/around/spec'