frankfurter/lib/snapshot.rb

50 lines
847 B
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
class Snapshot
2012-11-23 15:13:49 +01:00
include Virtus
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
2013-04-30 00:56:40 +02:00
self.date = if date
Currency.where("date <= '#{date}'").order(:date).last.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)
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