Module: AggtiveRecord::EggScopes::Collation::Rate::ClassMethods

Defined in:
lib/aggtive_record/egg_scopes/collation/rate_per.rb

Overview

Public: a rate expects that ActiveRelation has a grouping self is a ActiveRecord scope

Instance Method Summary collapse

Instance Method Details

#rate_per(time_period, timespan_in_seconds = nil) ⇒ Object

Public

Returns float indicating rate of records per given time period



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/aggtive_record/egg_scopes/collation/rate_per.rb', line 16

def rate_per(time_period, timespan_in_seconds = nil)

  # tk: this may be unnecessary
  records = self.scoped.to_a

   #e.g. whatever is passed in, or all of them from the beginning to end of reconrds
  timespan_in_seconds ||= self.timespan_to_now(records)

  # return 0 if no timespan_in_seconds
  return 0 if timespan_in_seconds.to_i == 0

  # eg. :hour is 3600 seconds
  time_period_in_secs = AggtiveRecord::Time.to_seconds(time_period)

  # if the rate query is #per_year, and the only record was created 1 day ago
  #   then the rate should be _no greater_ than 1 per year (as opposed to 365 per year)
  time_denominator = [time_period_in_secs, timespan_in_seconds].max

          
  return records.size.to_f * time_period_in_secs / time_denominator
end