Class: SourceMonitor::Analytics::SourceActivityRates

Inherits:
Object
  • Object
show all
Defined in:
lib/source_monitor/analytics/source_activity_rates.rb

Constant Summary collapse

DEFAULT_LOOKBACK =
14.days

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope: SourceMonitor::Source.all, lookback: DEFAULT_LOOKBACK, now: Time.current) ⇒ SourceActivityRates

Returns a new instance of SourceActivityRates.



8
9
10
11
12
# File 'lib/source_monitor/analytics/source_activity_rates.rb', line 8

def initialize(scope: SourceMonitor::Source.all, lookback: DEFAULT_LOOKBACK, now: Time.current)
  @scope = scope
  @lookback = lookback
  @now = now
end

Class Method Details

.rate_for(source, lookback: DEFAULT_LOOKBACK, now: Time.current) ⇒ Object



30
31
32
33
34
# File 'lib/source_monitor/analytics/source_activity_rates.rb', line 30

def self.rate_for(source, lookback: DEFAULT_LOOKBACK, now: Time.current)
  return 0.0 unless source

  new(scope: Array(source), lookback:, now:).per_source_rates[source.id] || 0.0
end

Instance Method Details

#per_source_ratesObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/source_monitor/analytics/source_activity_rates.rb', line 14

def per_source_rates
  return {} if source_ids.empty?

  counts = SourceMonitor::Item
    .where(source_id: source_ids)
    .where("created_at >= ?", window_start)
    .group(:source_id)
    .count

  days = [ lookback.in_days, 1 ].max

  counts.transform_values { |count| count.to_f / days }.tap do |results|
    source_ids.each { |source_id| results[source_id] ||= 0.0 }
  end
end