base_dimension.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # frozen_string_literal: true
  2. class Admin::Metrics::Dimension::BaseDimension
  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, limit, params)
  10. @start_at = start_at&.to_datetime
  11. @end_at = end_at&.to_datetime
  12. @limit = limit&.to_i
  13. @params = params
  14. @loaded = false
  15. end
  16. def key
  17. raise NotImplementedError
  18. end
  19. def cache_key
  20. ["metrics/dimension/#{key}", @start_at, @end_at, @limit, canonicalized_params].join(';')
  21. end
  22. def data
  23. load
  24. end
  25. def self.model_name
  26. self.class.name
  27. end
  28. def read_attribute_for_serialization(key)
  29. send(key) if respond_to?(key)
  30. end
  31. protected
  32. def load
  33. unless loaded?
  34. @values = Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) { perform_query }
  35. @loaded = true
  36. end
  37. @values
  38. end
  39. def perform_query
  40. raise NotImplementedError
  41. end
  42. def time_period
  43. (@start_at..@end_at)
  44. end
  45. def params
  46. {}
  47. end
  48. def canonicalized_params
  49. params.to_h.to_a.sort_by { |k, _v| k.to_s }.map { |k, v| "#{k}=#{v}" }.join(';')
  50. end
  51. end