about summary refs log tree commit diff
path: root/app/lib/admin/metrics/measure/base_measure.rb
blob: e33a6c494f918cfe424a21a92d3f6f729fd27db8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# frozen_string_literal: true

class Admin::Metrics::Measure::BaseMeasure
  CACHE_TTL = 5.minutes.freeze

  def self.with_params?
    false
  end

  attr_reader :loaded

  alias loaded? loaded

  def initialize(start_at, end_at, params)
    @start_at = start_at&.to_datetime
    @end_at   = end_at&.to_datetime
    @params   = params
    @loaded   = false
  end

  def cache_key
    ["metrics/measure/#{key}", @start_at, @end_at, canonicalized_params].join(';')
  end

  def key
    raise NotImplementedError
  end

  def unit
    nil
  end

  def total_in_time_range?
    true
  end

  def total
    load[:total]
  end

  def previous_total
    load[:previous_total]
  end

  def data
    load[:data]
  end

  def self.model_name
    self.class.name
  end

  def read_attribute_for_serialization(key)
    send(key) if respond_to?(key)
  end

  protected

  def load
    unless loaded?
      @values = Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) { perform_queries }.with_indifferent_access
      @loaded = true
    end

    @values
  end

  def perform_queries
    {
      total: perform_total_query,
      previous_total: perform_previous_total_query,
      data: perform_data_query,
    }
  end

  def perform_total_query
    raise NotImplementedError
  end

  def perform_previous_total_query
    raise NotImplementedError
  end

  def perform_data_query
    raise NotImplementedError
  end

  def time_period
    (@start_at..@end_at)
  end

  def previous_time_period
    ((@start_at - length_of_period)..(@end_at - length_of_period))
  end

  def length_of_period
    @length_of_period ||= @end_at - @start_at
  end

  def params
    {}
  end

  def canonicalized_params
    params.to_h.to_a.sort_by { |k, _v| k.to_s }.map { |k, v| "#{k}=#{v}" }.join(';')
  end
end