Module: ArLazyPreload::Relation

Defined in:
lib/ar_lazy_preload/active_record/relation.rb

Overview

ActiveRecord::Relation patch with lazy preloading support

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#lazy_preload_valuesObject



64
65
66
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 64

def lazy_preload_values
  @lazy_preload_values ||= []
end

#preloads_associations_lazily=(value) ⇒ Object (writeonly)

Sets the attribute preloads_associations_lazily

Parameters:

  • value

    the value to set the attribute preloads_associations_lazily to.



8
9
10
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 8

def preloads_associations_lazily=(value)
  @preloads_associations_lazily = value
end

Instance Method Details

#lazy_preload(*args) ⇒ Object

Specify relationships to be loaded lazily when association is loaded for the first time. For example:

users = User.lazy_preload(:posts)
users.each do |user|
  user.first_name
end

will cause only one SQL request to load users, while

users = User.lazy_preload(:posts)
users.each do |user|
  user.posts.map(&:id)
end

will make an additional query.



53
54
55
56
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 53

def lazy_preload(*args)
  check_if_method_has_arguments!(:lazy_preload, args)
  spawn.lazy_preload!(*args)
end

#lazy_preload!(*args) ⇒ Object



58
59
60
61
62
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 58

def lazy_preload!(*args)
  args.flatten!
  self.lazy_preload_values += args
  self
end

#loadObject

Enhanced #load method will check if association has not been loaded yet and add a context for lazy preloading to loaded each record



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 12

def load
  need_context = !loaded?
  result = super
  if need_context
    Context.register(
      records: ar_lazy_preload_records,
      association_tree: lazy_preload_values,
      auto_preload: preloads_associations_lazily?
    )
  end
  result
end

#preload_associations_lazilyObject

Lazily autoloads all associations. For example:

users = User.preload_associations_lazily
users.each do |user|
  user.posts.flat_map {|post| post.comments.map(&:id)}
end

Same effect can be achieved by User.lazy_preload(posts: :comments)



33
34
35
# File 'lib/ar_lazy_preload/active_record/relation.rb', line 33

def preload_associations_lazily
  spawn.tap { |relation| relation.preloads_associations_lazily = true }
end