1
0

base_measure.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Measure::BaseMeasure
  3. CACHE_TTL = 5.minutes.freeze
  4. def self.with_params?
  5. false
  6. end
  7. attr_reader :loaded
  8. alias loaded? loaded
  9. def initialize(start_at, end_at, params)
  10. @start_at = start_at&.to_datetime
  11. @end_at = end_at&.to_datetime
  12. @params = params
  13. @loaded = false
  14. end
  15. def cache_key
  16. ["metrics/measure/#{key}", @start_at, @end_at, canonicalized_params].join(';')
  17. end
  18. def key
  19. raise NotImplementedError
  20. end
  21. def unit
  22. nil
  23. end
  24. def total_in_time_range?
  25. true
  26. end
  27. def total
  28. load[:total]
  29. end
  30. def previous_total
  31. load[:previous_total]
  32. end
  33. def data
  34. load[:data]
  35. end
  36. def self.model_name
  37. self.class.name
  38. end
  39. def read_attribute_for_serialization(key)
  40. send(key) if respond_to?(key)
  41. end
  42. protected
  43. def load
  44. unless loaded?
  45. @values = Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) { perform_queries }.with_indifferent_access
  46. @loaded = true
  47. end
  48. @values
  49. end
  50. def perform_queries
  51. {
  52. total: perform_total_query,
  53. previous_total: perform_previous_total_query,
  54. data: perform_data_query,
  55. }
  56. end
  57. def perform_total_query
  58. raise NotImplementedError
  59. end
  60. def perform_previous_total_query
  61. raise NotImplementedError
  62. end
  63. def perform_data_query
  64. raise NotImplementedError
  65. end
  66. def time_period
  67. (@start_at..@end_at)
  68. end
  69. def previous_time_period
  70. ((@start_at - length_of_period)..(@end_at - length_of_period))
  71. end
  72. def length_of_period
  73. @length_of_period ||= @end_at - @start_at
  74. end
  75. def params
  76. {}
  77. end
  78. def canonicalized_params
  79. params.to_h.to_a.sort_by { |k, _v| k.to_s }.map { |k, v| "#{k}=#{v}" }.join(';')
  80. end
  81. end