Skip to content
This repository has been archived by the owner on Mar 2, 2024. It is now read-only.

Commit

Permalink
Save Calculations as Instance Variables
Browse files Browse the repository at this point in the history
In order to lighten the load on the DB when using Metric Objects we now
calculate the values when it is initialized.
  • Loading branch information
Michael Dijkstra committed Aug 7, 2014
1 parent 80b6c43 commit d34bd16
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
10 changes: 8 additions & 2 deletions lib/totalizer/metric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ class Metric
def initialize params
@params = params
validate!
calculate!
end

def change
Expand All @@ -22,7 +23,7 @@ def filter
end

def ids
calculate
@ids
end

def map
Expand All @@ -34,7 +35,7 @@ def model
end

def previous_ids
calculate(2)
@previous_ids
end

def previous_value
Expand All @@ -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
Expand Down
3 changes: 1 addition & 2 deletions spec/lib/totalizer/metric_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit d34bd16

Please sign in to comment.