From 580e9156e6860ddc8d2af825167ff1b96bbdc132 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Fri, 22 May 2020 22:10:34 +0200 Subject: [PATCH] Implemented QuantityInput#lastBefore --- app/models/formula.rb | 17 ++++++++++++++--- app/models/quantity.rb | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/app/models/formula.rb b/app/models/formula.rb index a0fbc3c..e308734 100644 --- a/app/models/formula.rb +++ b/app/models/formula.rb @@ -49,9 +49,20 @@ class Formula < ActiveRecord::Base end def lastBefore(timepoints) - self.map{ BigDecimal(2000) } - last_timepoint = timepoints.max - @quantity.quantity_values.includes(:registry) + # NOTE: maybe optimize query, limiting range by min-max timepoints? + # impact on caching? + values = @quantity.values.includes(:registry) + .map { |qv| [qv.registry.completed_at, qv.value] }.sort_by(&:first) + + return [nil]*timepoints.length if values.empty? + + vindex = 0 + lastval = nil + timepoints.each_with_index.sort_by { |t, i| t || Time.current }.map do |time, index| + #lastval = values[vindex++].last while values[vindex].first <= time + vindex += values[vindex..-1].find_all { |vtime, v| lastval = v; vtime <= time }.length + [lastval, index] + end.sort_by(&:last).transpose.first end end diff --git a/app/models/quantity.rb b/app/models/quantity.rb index ef5dcd1..a825e0e 100644 --- a/app/models/quantity.rb +++ b/app/models/quantity.rb @@ -9,7 +9,7 @@ class Quantity < ActiveRecord::Base belongs_to :project, required: false has_many :nutrients, dependent: :restrict_with_error has_many :readouts, dependent: :restrict_with_error - has_many :quantity_values, dependent: :restrict_with_error + has_many :values, class_name: 'QuantityValue', dependent: :restrict_with_error has_many :exposures, dependent: :destroy has_one :formula, inverse_of: :quantity, dependent: :destroy, validate: true