BigW Consortium Gitlab

attributes_finder.rb 1.3 KB
Newer Older
1 2 3
module Gitlab
  module ImportExport
    class AttributesFinder
4
      def initialize(included_attributes:, excluded_attributes:, methods:)
5 6
        @included_attributes = included_attributes || {}
        @excluded_attributes = excluded_attributes || {}
7
        @methods = methods || {}
8 9 10 11 12 13 14
      end

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

15 16 17
      def parse(model_object)
        parsed_hash = find_attributes_only(model_object)
        yield parsed_hash unless parsed_hash.empty?
18 19 20 21 22 23 24 25 26 27 28 29
      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

30 31 32 33 34
      def find_method(value)
        key = key_from_hash(value)
        @methods[key].nil? ? {} : { methods: @methods[key] }
      end

35 36
      private

37
      def find_attributes_only(value)
38
        find_included(value).merge(find_excluded(value)).merge(find_method(value))
39 40
      end

41 42 43 44 45
      def key_from_hash(value)
        value.is_a?(Hash) ? value.keys.first : value
      end
    end
  end
46
end