Add scopes for common behavior
authorMarcel Hlopko <marcel@hlopko.com>
Tue, 28 Oct 2014 17:28:57 +0100
changeset 237 195fca969b9a
parent 236 2565b32e93b3
child 238 6ec4c90dfc1a
Add scopes for common behavior
web/app/models/benchmark_info.rb
web/app/models/benchmark_result.rb
--- a/web/app/models/benchmark_info.rb	Tue Oct 28 17:21:19 2014 +0100
+++ b/web/app/models/benchmark_info.rb	Tue Oct 28 17:28:57 2014 +0100
@@ -20,9 +20,8 @@
 
   def to_results_json_for_configuration(configuration)
     data = benchmark_results.
-      includes(:benchmark_batch, :benchmark_durations).
-      joins(:benchmark_batch).
-      where("benchmark_batches.benchmark_configuration_id = ?", configuration.id).
+      for_configuration_id(configuration.id).
+      with_batch_and_duration_preloaded.
       map(&:to_json)
 
     { name: name, data: data }
@@ -30,12 +29,12 @@
 
   def latest_result_for_configuration(configuration)
     benchmark_results.
-      includes(:benchmark_batch, :benchmark_durations).
-      joins(:benchmark_batch).
-      where("benchmark_batches.benchmark_configuration_id = ?", configuration.id).
-      order("benchmark_batches.performed_at desc, benchmark_batches.created_at desc").
+      for_configuration_id(configuration.id).
+      with_batch_and_duration_preloaded.
+      newest_first.
       first
   end
+
 end
 
 # == Schema Information
--- a/web/app/models/benchmark_result.rb	Tue Oct 28 17:21:19 2014 +0100
+++ b/web/app/models/benchmark_result.rb	Tue Oct 28 17:28:57 2014 +0100
@@ -5,6 +5,18 @@
   has_many :benchmark_durations, dependent: :destroy, inverse_of: :benchmark_result
   has_many :benchmark_parameters, dependent: :destroy, inverse_of: :benchmark_result
 
+  scope :for_configuration_id, -> (configuration_id) do
+    joins(:benchmark_batch).
+      where("benchmark_batches.benchmark_configuration_id = ?", configuration_id)
+  end
+
+  scope :with_batch_and_duration_preloaded, -> do
+    includes(:benchmark_batch, :benchmark_durations)
+  end
+
+  scope :newest_first, -> do
+    order("benchmark_batches.performed_at desc, benchmark_batches.created_at desc")
+  end
 
   def average_duration
     sum = benchmark_durations.inject(0) { |acc, val| acc += val.duration }