From 6faa26583405e3d39c3f93286531d3d585f54dd4 Mon Sep 17 00:00:00 2001 From: Hakan Ensari Date: Wed, 20 Nov 2024 14:22:08 +0100 Subject: [PATCH] Refactor date lookup --- lib/day.rb | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/lib/day.rb b/lib/day.rb index ffde2a7..4f15f86 100644 --- a/lib/day.rb +++ b/lib/day.rb @@ -3,23 +3,17 @@ class Day < Sequel::Model dataset_module do def latest(date = Date.today) - where(date: select(:date).where(Sequel[:date] <= date) - .order(Sequel.desc(:date)) - .limit(1)) + where(date: _nearest_date_with_rates(date)) end - # Returns rates for a given date interval - # - # If the start date falls on a holiday/weekend, rates start from the closest preceding business day. def between(interval) return where(false) if interval.begin > Date.today - previous_date = select(:date) - .where(Sequel[:date] <= interval.begin) - .order(Sequel.desc(:date)) - .limit(1) - - where(Sequel.expr(:date) >= Sequel.function(:coalesce, previous_date, interval.begin)) + where(Sequel.expr(:date) >= Sequel.function( + :coalesce, + _nearest_date_with_rates(interval.begin), + interval.begin, + )) .where(Sequel.expr(:date) <= interval.end) end @@ -31,5 +25,12 @@ class Day < Sequel::Model ) .join(Sequel.function(:jsonb_each, :rates).lateral.as(:rates), true) end + + def _nearest_date_with_rates(date) + select(:date) + .where(Sequel[:date] <= date) + .order(Sequel.desc(:date)) + .limit(1) + end end end