2015-12-30 20:52:02 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
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-08-30 12:54:13 +02:00
|
|
|
class Quote
|
|
|
|
include Virtus.value_object
|
|
|
|
|
2016-04-11 15:26:49 +02:00
|
|
|
Invalid = Class.new(StandardError)
|
|
|
|
|
2016-04-11 15:14:10 +02:00
|
|
|
DEFAULT_BASE = 'EUR'.freeze
|
2015-08-30 12:54:13 +02:00
|
|
|
|
|
|
|
values do
|
|
|
|
attribute :base, String, default: DEFAULT_BASE
|
2015-09-15 13:02:49 +02:00
|
|
|
attribute :date, Date, default: proc { Currency.current_date }
|
2015-12-22 20:46:10 +01:00
|
|
|
attribute :rates, Hash, default: :find_rates, lazy: true
|
2012-11-20 17:36:12 +01:00
|
|
|
end
|
|
|
|
|
2012-11-23 15:13:49 +01:00
|
|
|
private
|
|
|
|
|
2015-08-31 11:56:01 +02:00
|
|
|
def base=(base)
|
|
|
|
base.upcase!
|
|
|
|
super base
|
|
|
|
end
|
|
|
|
|
2015-08-30 12:54:13 +02:00
|
|
|
def date=(date)
|
|
|
|
current_date = Currency.current_date_before(date)
|
2016-04-11 15:26:49 +02:00
|
|
|
raise Invalid, 'Date too old' unless current_date
|
2015-08-30 12:54:13 +02:00
|
|
|
super current_date
|
2016-04-11 15:26:49 +02:00
|
|
|
rescue Sequel::DatabaseError => ex
|
|
|
|
if ex.wrapped_exception.is_a?(PG::DatetimeFieldOverflow)
|
|
|
|
raise Invalid, 'Invalid date'
|
|
|
|
else
|
|
|
|
raise
|
|
|
|
end
|
2015-08-30 12:54:13 +02:00
|
|
|
end
|
|
|
|
|
2015-08-31 11:56:01 +02:00
|
|
|
def find_rates
|
|
|
|
quoted_against_default_base? ? find_default_rates : find_rebased_rates
|
|
|
|
end
|
|
|
|
|
|
|
|
def quoted_against_default_base?
|
|
|
|
base == DEFAULT_BASE
|
|
|
|
end
|
|
|
|
|
|
|
|
def find_default_rates
|
2013-04-30 00:56:40 +02:00
|
|
|
Currency.where(date: date).reduce({}) do |rates, currency|
|
2015-08-31 11:56:01 +02:00
|
|
|
rates.update(currency.to_h)
|
2013-04-30 00:56:40 +02:00
|
|
|
end
|
2012-11-20 17:36:12 +01:00
|
|
|
end
|
|
|
|
|
2015-08-31 11:56:01 +02:00
|
|
|
def find_rebased_rates
|
|
|
|
rates = find_default_rates
|
|
|
|
denominator = rates.update(DEFAULT_BASE => 1.0).delete(base)
|
2016-04-11 15:26:49 +02:00
|
|
|
raise Invalid, 'Invalid base' unless denominator
|
2015-08-31 11:56:01 +02:00
|
|
|
rates.each do |iso_code, rate|
|
|
|
|
rates[iso_code] = round_rate(rate / denominator)
|
2012-11-21 13:31:17 +01:00
|
|
|
end
|
|
|
|
|
2012-11-23 15:13:49 +01:00
|
|
|
rates
|
2012-11-20 17:36:12 +01:00
|
|
|
end
|
|
|
|
|
2016-04-11 15:14:10 +02:00
|
|
|
# I'm mimicking the apparent convention of the ECB here.
|
2015-08-31 11:56:01 +02:00
|
|
|
def round_rate(rate)
|
2016-04-11 15:14:10 +02:00
|
|
|
Float(format('%.5g', rate))
|
2012-11-20 17:36:12 +01:00
|
|
|
end
|
|
|
|
end
|