frankfurter/lib/snapshot.rb

60 lines
958 B
Ruby
Raw Normal View History

2012-11-20 17:36:12 +01:00
require_relative 'db'
2012-11-23 15:13:49 +01:00
require 'virtus'
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
2012-11-23 15:13:49 +01:00
attribute :base, String, default: 'EUR'
2012-11-28 03:16:33 +01:00
attribute :date, Date
2012-11-23 15:13:49 +01:00
def quote
2012-11-28 03:16:33 +01:00
self.date =
if date
Currency
.where("date <= '#{date}'")
.order(:date)
.last
.date
else
Currency.last_date
end
2012-11-23 15:13:49 +01: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
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-21 13:33:52 +01:00
# Ugly as fuck.
2012-11-23 15:13:49 +01:00
def rebase(rates)
if base.upcase! != 'EUR'
denominator = rates
2012-11-21 13:31:17 +01:00
.update('EUR' => 1.0)
2012-11-23 15:13:49 +01:00
.delete base
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
2012-11-23 15:13:49 +01:00
rate.round 2
2012-11-23 16:11:00 +01:00
elsif rate > 10
2012-11-23 15:13:49 +01:00
rate.round 3
else
rate.round 4
end
2012-11-20 17:36:12 +01:00
end
end