Class: Rails::Surrender::Render::Resource::InclusionMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/surrender/render/resource/inclusion_mapper.rb

Overview

Builds a complete map of the resources needed to fulfill the request, for supplying to ActiveRecord.includes

Defined Under Namespace

Classes: Element

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource_class:, config:) ⇒ InclusionMapper

InclusionMapper is designed to recursively crawl through the model rendering structure and build a hash that ActiveRecord can use to eager load ALL of the data we’re going to render, to prevent N+1 queries



14
15
16
17
# File 'lib/rails/surrender/render/resource/inclusion_mapper.rb', line 14

def initialize(resource_class:, config:)
  @resource_class = resource_class
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



9
10
11
# File 'lib/rails/surrender/render/resource/inclusion_mapper.rb', line 9

def config
  @config
end

#resource_classObject (readonly)

Returns the value of attribute resource_class.



9
10
11
# File 'lib/rails/surrender/render/resource/inclusion_mapper.rb', line 9

def resource_class
  @resource_class
end

Instance Method Details

#parseObject



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
# File 'lib/rails/surrender/render/resource/inclusion_mapper.rb', line 19

def parse
  config.history.push resource_class
  includes = []

  config.expanding_elements.each do |element|
    item_config = Configuration.new(
      resource_class: element.klass,
      user_include: config.nested_user_includes[element.name] || [],
      ctrl_include: config.nested_ctrl_includes[element.name] || [],
      user_exclude: config.nested_user_excludes[element.name] || [],
      ctrl_exclude: config.nested_ctrl_excludes[element.name] || [],
      history: config.history.dup.push(element.klass)
    )

    nested = if element.continue
               InclusionMapper.new(resource_class: element.klass, config: item_config).parse
             else
               []
             end

    includes << (nested.size.zero? ? element.name : { element.name => nested })
  end

  includes.sort_by { |x| x.is_a?(Symbol) ? 0 : 1 }
end