Module: ActiveRecordCustomPreloader::WithContextDependentLoading

Extended by:
ActiveSupport::Concern
Defined in:
lib/active_record_custom_preloader/with_context_dependent_loading.rb

Instance Method Summary collapse

Instance Method Details

#associations_by_record(grouped_associations, parent_record) ⇒ Object

returns associations for provided parent_record. array for has_many and model or nil for has_one.



67
68
69
70
71
# File 'lib/active_record_custom_preloader/with_context_dependent_loading.rb', line 67

def associations_by_record(grouped_associations, parent_record)
  key = parent_record.public_send(record_group_key)
  associations = grouped_associations[key]
  to_many ? associations || [] : associations&.first
end

#fetch_association(parent_records) ⇒ Object



73
74
75
76
# File 'lib/active_record_custom_preloader/with_context_dependent_loading.rb', line 73

def fetch_association(parent_records)
  scope = scoped_collection(parent_records)
  scope.to_a.group_by(&association_group_key)
end

#preload(parent_records) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/active_record_custom_preloader/with_context_dependent_loading.rb', line 78

def preload(parent_records)
  grouped_associations = fetch_association(parent_records)
  parent_records.each do |parent_record|
    value = associations_by_record(grouped_associations, parent_record)
    parent_record._set_custom_preloaded_value(name, value)
  end
end

#scoped_collection(_parent_records) ⇒ Object

should return associations scope. must be overridden.



61
62
63
# File 'lib/active_record_custom_preloader/with_context_dependent_loading.rb', line 61

def scoped_collection(_parent_records)
  raise NotImplementedError.new 'override #scoped_collection in a subclass'
end