summaryrefslogtreecommitdiff
path: root/lib/api/helpers/custom_attributes.rb
blob: 88208226c4005d2cd0f3d23c01627d26ea226be4 (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
# frozen_string_literal: true

module API
  module Helpers
    module CustomAttributes
      extend ActiveSupport::Concern

      included do
        helpers do
          params :with_custom_attributes do
            optional :with_custom_attributes, type: Boolean, default: false, desc: 'Include custom attributes in the response'

            optional :custom_attributes, type: Hash,
                                         desc: 'Filter with custom attributes'
          end

          # rubocop: disable CodeReuse/ActiveRecord
          def with_custom_attributes(collection_or_resource, options = {})
            options = options.merge(
              with_custom_attributes: params[:with_custom_attributes] &&
                can?(current_user, :read_custom_attribute)
            )

            if options[:with_custom_attributes] && collection_or_resource.is_a?(ActiveRecord::Relation)
              collection_or_resource = collection_or_resource.includes(:custom_attributes)
            end

            [collection_or_resource, options]
          end
          # rubocop: enable CodeReuse/ActiveRecord
        end
      end
    end
  end
end