summaryrefslogtreecommitdiff
path: root/lib/gitlab/integrations/sti_type.rb
blob: f347db7bc8cb4c651042c2bb87491bff300f93e5 (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
59
60
61
62
63
64
65
66
# frozen_string_literal: true

module Gitlab
  module Integrations
    class StiType < ActiveRecord::Type::String
      NAMESPACED_INTEGRATIONS = %w[
        Asana Assembla Bamboo Bugzilla Buildkite Campfire Confluence CustomIssueTracker Datadog
        Discord DroneCi EmailsOnPush Ewm ExternalWiki Flowdock HangoutsChat Harbor Irker Jenkins Jira Mattermost
        MattermostSlashCommands MicrosoftTeams MockCi MockMonitoring Packagist PipelinesEmail Pivotaltracker
        Prometheus Pushover Redmine Shimo Slack SlackSlashCommands Teamcity UnifyCircuit WebexTeams Youtrack Zentao
      ].to_set.freeze

      def self.namespaced_integrations
        NAMESPACED_INTEGRATIONS
      end

      def cast(value)
        new_cast(value) || super
      end

      def serialize(value)
        new_serialize(value) || super
      end

      def deserialize(value)
        value
      end

      def changed?(original_value, value, _new_value_before_type_cast)
        original_value != serialize(value)
      end

      def changed_in_place?(original_value_for_database, value)
        original_value_for_database != serialize(value)
      end

      private

      def new_cast(value)
        value = prepare_value(value)
        return unless value

        stripped_name = value.delete_suffix('Service')
        return unless self.class.namespaced_integrations.include?(stripped_name)

        "Integrations::#{stripped_name}"
      end

      def new_serialize(value)
        value = prepare_value(value)
        return unless value&.starts_with?('Integrations::')

        "#{value.delete_prefix('Integrations::')}Service"
      end

      # Returns value cast to a `String`, or `nil` if value is `nil`.
      def prepare_value(value)
        return value if value.nil? || value.is_a?(String)

        value.to_s
      end
    end
  end
end

Gitlab::Integrations::StiType.prepend_mod