summaryrefslogtreecommitdiff
path: root/lib/gitlab/usage/metric.rb
blob: f3469209f486eb235b973dc0549ef1d7b5352927 (plain)
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
# frozen_string_literal: true

module Gitlab
  module Usage
    class Metric
      include ActiveModel::Model

      InvalidMetricError = Class.new(RuntimeError)

      attr_accessor :key_path, :value

      validates :key_path, presence: true

      def definition
        self.class.definitions[key_path]
      end

      def unflatten_key_path
        unflatten(key_path.split('.'), value)
      end

      class << self
        def definitions
          @definitions ||= Gitlab::Usage::MetricDefinition.definitions
        end

        def dictionary
          definitions.map { |key, definition| definition.to_dictionary }
        end
      end

      private

      def unflatten(keys, value)
        loop do
          value = { keys.pop.to_sym => value }
          break if keys.blank?
        end
        value
      end
    end
  end
end