File: nested_exposures.rb

package info (click to toggle)
ruby-grape-entity 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 456 kB
  • sloc: ruby: 3,335; makefile: 6
file content (83 lines) | stat: -rw-r--r-- 2,101 bytes parent folder | download | duplicates (2)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true

module Grape
  class Entity
    module Exposure
      class NestingExposure
        class NestedExposures
          include Enumerable

          def initialize(exposures)
            @exposures = exposures
            @deep_complex_nesting = nil
          end

          def find_by(attribute)
            @exposures.find { |e| e.attribute == attribute }
          end

          def select_by(attribute)
            @exposures.select { |e| e.attribute == attribute }
          end

          def <<(exposure)
            reset_memoization!
            @exposures << exposure
          end

          def delete_by(*attributes)
            reset_memoization!
            @exposures.reject! { |e| attributes.include? e.attribute }
            @exposures
          end

          def clear
            reset_memoization!
            @exposures.clear
          end

          # rubocop:disable Style/DocumentDynamicEvalDefinition
          %i[
            each
            to_ary to_a
            all?
            select
            each_with_object
            \[\]
            ==
            size
            count
            length
            empty?
          ].each do |name|
            class_eval <<-RUBY, __FILE__, __LINE__ + 1
              def #{name}(*args, &block)
                @exposures.#{name}(*args, &block)
              end
            RUBY
          end
          # rubocop:enable Style/DocumentDynamicEvalDefinition

          # Determine if we have any nesting exposures with the same name.
          def deep_complex_nesting?(entity)
            if @deep_complex_nesting.nil?
              all_nesting = select(&:nesting?)
              @deep_complex_nesting =
                all_nesting
                .group_by { |exposure| exposure.key(entity) }
                .any? { |_key, exposures| exposures.length > 1 }
            else
              @deep_complex_nesting
            end
          end

          private

          def reset_memoization!
            @deep_complex_nesting = nil
          end
        end
      end
    end
  end
end