Welcome to mirror list, hosted at ThFree Co, Russian Federation.

enum_inheritance.rb « concerns « models « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1df1f3d43fdd297cc573fc2cfaf0e22134839a2f (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

module EnumInheritance
  # == STI through Enum
  #
  # WARNING: Usage of STI is heavily discouraged: https://docs.gitlab.com/ee/development/database/single_table_inheritance.html
  #
  # Active Record allows definition of STI through the <tt>Base.inheritance_column</tt>. However, this stores the class
  # name as string into the record, which is heavy and unnecessary. EnumInheritance adapts ActiveRecord to use an enum
  # instead.
  #
  # Details:
  # - Correct class mapping is specified in the <tt>self.sti_type_map<\tt>, which maps the symbol of the type to
  # a fully classified class as string.
  # - If the type passed does not have an specified class, then the class will be the base class
  #
  # Example
  #   class Animal
  #     include EnumInheritable
  #
  #     enum animal_type: {
  #       dog: 1,
  #       cat: 2,
  #       bird: 3
  #     }
  #
  #     def self.inheritance_column_to_class_map = {
  #       dog: 'Animals::Dog',
  #       cat: 'Animals::Cat'
  #     }
  #
  #     def self.inheritance_column = 'animal_type'
  #   end
  #
  #   class Animals::Dog < Animal; end
  #   class Animals::Cat < Animal; end
  extend ActiveSupport::Concern

  included do
    def self.sti_class_to_enum_map = inheritance_column_to_class_map.invert
  end

  class_methods do
    extend ::Gitlab::Utils::Override

    def inheritance_column_to_class_map = {}.freeze

    override :sti_class_for
    def sti_class_for(type_name)
      inheritance_column_to_class_map[type_name.to_sym]&.constantize || base_class
    end

    override :sti_name
    def sti_name
      sti_class_to_enum_map[name].to_s
    end
  end
end