Module: Dase::PreloaderMethods

Included in:
Dase::Preloader::HasMany, Dase::Preloader::HasManyThrough
Defined in:
lib/dase/preloader_methods.rb

Instance Method Summary collapse

Instance Method Details

#apply_association_options(options, scope) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dase/preloader_methods.rb', line 24

def apply_association_options(options, scope)
  proc = options.delete(:proc)

  # applying proc syntax: -> {...}
  scope = scope.instance_exec(&proc) if proc

  options.slice(*VALID_ASSOCIATION_OPTIONS).each do |key, value|
    scope = scope.send(key, value)
  end

  scope
end

#foreign_keyObject



3
4
5
# File 'lib/dase/preloader_methods.rb', line 3

def foreign_key
  reflection.klass.arel_table[reflection.foreign_key]
end

#preload(preloader) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/dase/preloader_methods.rb', line 7

def preload(preloader)
  pk = model.primary_key.to_sym
  ids = owners.map(&pk)
  scope = records_for(ids)

  # applying options like :where => ... or :conditions => ..., or -> {....}
  scope = apply_association_options(preloader.options.clone, scope)

  # the actual magic of attaching counters to the records comes here
  counters_hash = scope.group(foreign_key).count(Arel.star)
  owners.each do |owner|
    owner.define_singleton_method(preloader.options[:as]) do
      counters_hash[owner[pk]] || 0
    end
  end
end