summaryrefslogtreecommitdiff
path: root/lib/gitlab/import_export/attributes_finder.rb
blob: 42cd94add794686a862dc2b7c4351644293e7fc0 (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
# frozen_string_literal: true

module Gitlab
  module ImportExport
    class AttributesFinder
      def initialize(included_attributes:, excluded_attributes:, methods:)
        @included_attributes = included_attributes || {}
        @excluded_attributes = excluded_attributes || {}
        @methods = methods || {}
      end

      def find(model_object)
        parsed_hash = find_attributes_only(model_object)
        parsed_hash.empty? ? model_object : { model_object => parsed_hash }
      end

      def parse(model_object)
        parsed_hash = find_attributes_only(model_object)
        yield parsed_hash unless parsed_hash.empty?
      end

      def find_included(value)
        key = key_from_hash(value)
        @included_attributes[key].nil? ? {} : { only: @included_attributes[key] }
      end

      def find_excluded(value)
        key = key_from_hash(value)
        @excluded_attributes[key].nil? ? {} : { except: @excluded_attributes[key] }
      end

      def find_method(value)
        key = key_from_hash(value)
        @methods[key].nil? ? {} : { methods: @methods[key] }
      end

      def find_excluded_keys(klass_name)
        @excluded_attributes[klass_name.to_sym]&.map(&:to_s) || []
      end

      private

      def find_attributes_only(value)
        find_included(value).merge(find_excluded(value)).merge(find_method(value))
      end

      def key_from_hash(value)
        value.is_a?(Hash) ? value.first.first : value
      end
    end
  end
end