Class: ApiMaker::Preloader

Inherits:
Object
  • Object
show all
Defined in:
lib/api_maker/preloader.rb

Instance Method Summary collapse

Constructor Details

#initialize(ability: nil, args: nil, collection:, data:, include_param:, records:, select:) ⇒ Preloader

Returns a new instance of Preloader.



2
3
4
5
6
7
8
9
10
# File 'lib/api_maker/preloader.rb', line 2

def initialize(ability: nil, args: nil, collection:, data:, include_param:, records:, select:)
  @ability = ability
  @args = args
  @collection = collection
  @data = data
  @include_param = include_param
  @records = records
  @select = select
end

Instance Method Details

#fill_dataObject



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
# File 'lib/api_maker/preloader.rb', line 12

def fill_data
  parsed = ApiMaker::RelationshipIncluder.parse(@include_param)
  return unless parsed

  parsed.each do |key, value|
    next unless key

    reflection = @collection.model.reflections[key]
    raise "Unknown reflection: #{@collection.model.name}##{key}" unless reflection

    fill_empty_relationships_for_key(reflection, key)
    preload_class = preload_class_for_key(reflection)

    preload_result = ApiMaker::Configuration.profile("Preloading #{reflection.klass.name} with #{preload_class.name}") do
      preload_class.new(
        ability: @ability,
        args: @args,
        collection: @collection,
        data: @data,
        records: @records,
        reflection: reflection,
        select: @select
      ).preload
    end

    next if value.blank? || preload_result.fetch(:collection).empty?

    ApiMaker::Preloader.new(
      ability: @ability,
      args: @args,
      data: @data,
      collection: preload_result.fetch(:collection),
      include_param: value,
      records: @data.fetch(:included),
      select: @select
    ).fill_data
  end
end