Class: Alchemy::ElementPreloader
- Inherits:
-
Object
- Object
- Alchemy::ElementPreloader
- Defined in:
- app/services/alchemy/element_preloader.rb
Overview
Preloads element trees with all associations and nested elements
This service efficiently loads element trees to avoid N+1 queries. It recursively preloads all nested elements to unlimited depth.
Instance Method Summary collapse
-
#call ⇒ Array<Element>
Preloads and returns the element tree with all associations loaded.
-
#initialize(page_version:) ⇒ ElementPreloader
constructor
A new instance of ElementPreloader.
Constructor Details
#initialize(page_version:) ⇒ ElementPreloader
Returns a new instance of ElementPreloader.
15 16 17 18 19 20 21 |
# File 'app/services/alchemy/element_preloader.rb', line 15 def initialize(page_version:) @page_version = page_version ActiveRecord::Associations::Preloader.new( records: [page_version], associations: {page: :language} ).call end |
Instance Method Details
#call ⇒ Array<Element>
Preloads and returns the element tree with all associations loaded
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'app/services/alchemy/element_preloader.rb', line 26 def call # Load all elements for the page version with associations all_elements = load_all_elements return [] if all_elements.empty? # Build parent -> children lookup and populate associations populate_nested_associations(all_elements) # Root elements are those without a parent root_elements = all_elements.values .select { |e| e.parent_element_id.nil? } .sort_by(&:position) return [] if root_elements.empty? (root_elements) root_elements end |