From d34bd163e8779d6854bad2738e548ce8fdb7bac2 Mon Sep 17 00:00:00 2001 From: Michael Dijkstra Date: Fri, 8 Aug 2014 07:37:02 +1000 Subject: [PATCH] Save Calculations as Instance Variables In order to lighten the load on the DB when using Metric Objects we now calculate the values when it is initialized. --- lib/totalizer/metric.rb | 10 ++++++++-- spec/lib/totalizer/metric_spec.rb | 3 +-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/totalizer/metric.rb b/lib/totalizer/metric.rb index e31bb62..003df79 100644 --- a/lib/totalizer/metric.rb +++ b/lib/totalizer/metric.rb @@ -3,6 +3,7 @@ class Metric def initialize params @params = params validate! + calculate! end def change @@ -22,7 +23,7 @@ def filter end def ids - calculate + @ids end def map @@ -34,7 +35,7 @@ def model end def previous_ids - calculate(2) + @previous_ids end def previous_value @@ -59,6 +60,11 @@ def build_date_range duration_multiplier start_date - (duration * duration_multiplier).days..start_date - (duration * (duration_multiplier - 1)).days end + def calculate! + @ids = calculate + @previous_ids = calculate(2) + end + def calculate duration_multiplier=1 model.where(filter).where(created_at: build_date_range(duration_multiplier)).map { |object| object.send(map) }.uniq end diff --git a/spec/lib/totalizer/metric_spec.rb b/spec/lib/totalizer/metric_spec.rb index 014faef..67ae170 100644 --- a/spec/lib/totalizer/metric_spec.rb +++ b/spec/lib/totalizer/metric_spec.rb @@ -7,8 +7,7 @@ end it "requires a valid filter" do - metric = Totalizer::Metric.new({ model: User, start_date: Date.today, duration: 7, filter: 'non_existant_field = true' }) - expect{metric.calculate}.to raise_exception + expect{ Totalizer::Metric.new({ model: User, start_date: Date.today, duration: 7, filter: 'non_existant_field = true' }) }.to raise_exception end end