Class: InstagramConnect::InsightSnapshot

Inherits:
ApplicationRecord show all
Defined in:
app/models/instagram_connect/insight_snapshot.rb

Overview

One reading of a set of metrics, kept because Meta's own retention is short and, for stories, measured in hours.

Constant Summary collapse

SUBJECT_TYPES =
%w[account media story].freeze
SOURCES =
%w[api webhook].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.record(account:, subject_type:, period:, period_start:, metrics:, captured_at:, subject_ref: nil, breakdown: nil, source: "api", empty: false, suppressed: false, error_code: nil) ⇒ Object

Upsert on the natural key. The API poller overwrites its own reading as a story accrues views; the webhook's final reading is a separate row because source is part of the key, so neither can clobber the other.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/models/instagram_connect/insight_snapshot.rb', line 22

def self.record(account:, subject_type:, period:, period_start:, metrics:, captured_at:,
                subject_ref: nil, breakdown: nil, source: "api", empty: false,
                suppressed: false, error_code: nil)
  snapshot = find_or_initialize_by(
    account_id: .id, subject_type: subject_type, subject_ref: subject_ref,
    period: period, period_start: period_start, breakdown: breakdown, source: source
  )
  snapshot.assign_attributes(
    metrics: metrics, captured_at: captured_at, empty: empty,
    suppressed: suppressed, error_code: error_code
  )
  snapshot.save!
  snapshot
end

Instance Method Details

#value(metric) ⇒ Object

nil means Meta did not report the metric, which is not the same as zero — so callers must never reach for a default here.



39
40
41
# File 'app/models/instagram_connect/insight_snapshot.rb', line 39

def value(metric)
  metrics.is_a?(Hash) ? metrics[metric.to_s] : nil
end