frankfurter/lib/snapshot.rb

54 lines
1.0 KiB
Ruby
Raw Normal View History

2012-11-23 15:13:49 +01:00
require 'virtus'
2014-03-14 13:08:48 +01:00
require 'currency'
2012-11-20 17:36:12 +01:00
2015-05-25 13:13:05 +02:00
# Quotes exchange rates on a specific date
2012-11-20 17:36:12 +01:00
class Snapshot
2014-03-14 13:20:12 +01:00
include Virtus.model
2012-11-21 13:44:33 +01:00
2013-04-30 00:56:40 +02:00
attribute :base, String, default: 'EUR'
attribute :date, Date
2012-11-23 15:13:49 +01:00
def quote
2015-05-25 13:13:05 +02:00
self.date =
if date
last_date = Currency.where("date <= '#{date}'").order(:date).last
fail ArgumentError, 'Date too old' unless last_date
last_date.date
else
Currency.last_date
end
2012-11-28 03:16:33 +01:00
2013-04-30 00:56:40 +02:00
attributes.merge(rates: rebase(rates))
2012-11-20 17:36:12 +01:00
end
2012-11-23 15:13:49 +01:00
private
def rates
2013-04-30 00:56:40 +02:00
Currency.where(date: date).reduce({}) do |rates, currency|
rates.update(currency.to_hash)
end
2012-11-20 17:36:12 +01:00
end
2012-11-23 15:13:49 +01:00
def rebase(rates)
if base.upcase! != 'EUR'
2013-04-30 00:56:40 +02:00
denominator = rates.update('EUR' => 1.0).delete(base)
2015-05-25 13:13:05 +02:00
fail ArgumentError, 'Invalid base' unless denominator
2012-11-23 15:13:49 +01:00
rates.each do |iso_code, rate|
rates[iso_code] = round(rate / denominator)
2012-11-21 13:31:17 +01:00
end
end
2012-11-23 15:13:49 +01:00
rates
2012-11-20 17:36:12 +01:00
end
2012-11-23 15:13:49 +01:00
def round(rate)
2012-11-23 16:11:00 +01:00
if rate > 100
2013-04-30 00:56:40 +02:00
rate.round(2)
2012-11-23 16:11:00 +01:00
elsif rate > 10
2013-04-30 00:56:40 +02:00
rate.round(3)
2012-11-23 15:13:49 +01:00
else
2013-04-30 00:56:40 +02:00
rate.round(4)
2012-11-23 15:13:49 +01:00
end
2012-11-20 17:36:12 +01:00
end
end