summaryrefslogtreecommitdiff
path: root/lib/gitlab/graphql/present.rb
blob: 3608cb4c0e8a63ccd743c3a552039862e3bab7bf (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
# frozen_string_literal: true

module Gitlab
  module Graphql
    module Present
      extend ActiveSupport::Concern
      prepended do
        def self.present_using(kls)
          @presenter_class = kls
        end

        def self.presenter_class
          @presenter_class || superclass.try(:presenter_class)
        end

        def self.present(object, attrs)
          klass = presenter_class
          return object if !klass || object.is_a?(klass)

          klass.new(object, **attrs)
        end
      end

      def unpresented
        unwrapped || object
      end

      def present(object_type, attrs)
        return unless object_type.respond_to?(:present)

        self.unwrapped ||= object
        # @object belongs to Schema::Object, which does not expose a writer.
        @object = object_type.present(unwrapped, attrs) # rubocop: disable Gitlab/ModuleWithInstanceVariables
      end

      private

      attr_accessor :unwrapped
    end
  end
end