app/models/punch.rb in punching_bag-0.2.0 vs app/models/punch.rb in punching_bag-0.3.0
- old
+ new
@@ -89,9 +89,21 @@
unless year_combo?
combine_with find_combo_for(:year)
end
end
+ def self.average_for(punchables)
+ if punchables.map(&:class).uniq.length != 1
+ raise ArgumentError, 'Punchables must all be of the same class'
+ end
+
+ sums = Punch.where(:punchable_type => punchables.first.class.to_s, :punchable_id => punchables.map(&:id)).group(:punchable_id).sum(:hits)
+
+ return 0 if sums.empty? # catch divide by zero
+
+ sums.values.inject(:+).to_f / sums.length
+ end
+
private
def set_defaults
if date = (self.starts_at ||= DateTime.now)
self.ends_at ||= date