Class: MongoMapper::EagerIncluder

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_mapper/eager_includer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record_or_records, association_name, &query_alteration_block) ⇒ EagerIncluder

Returns a new instance of EagerIncluder.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mongo_mapper/eager_includer.rb', line 10

def initialize(record_or_records, association_name, &query_alteration_block)
  if record_or_records.is_a? Plucky::Query
    raise "You must call `to_a` on `Plucky::Query` objects before passing to eager_include"
  end
  @records = Array(record_or_records).dup

  return if @records.length == 0
  @association_name = association_name.to_sym
  @query_alteration_block = query_alteration_block
  @association = @records.first.associations[@association_name]
  if !@association
    raise "Could not find association `#{association_name}` on instance of #{@records.first.class}"
  end
end

Class Method Details

.eager_include(record_or_records, *association_names, &query_alteration_block) ⇒ Object



4
5
6
7
8
# File 'lib/mongo_mapper/eager_includer.rb', line 4

def self.eager_include(record_or_records, *association_names, &query_alteration_block)
  association_names.each do |association_name|
    new(record_or_records, association_name, &query_alteration_block).eager_include
  end
end

Instance Method Details

#eager_includeObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mongo_mapper/eager_includer.rb', line 25

def eager_include
  # ignore records that have already had this assoication eager loaded
  @records.reject! do |record|
    record.instance_variable_defined?(instance_variable_name)
  end

  return if @records.length == 0

  @association_type = case @association.proxy_class.to_s
  when 'MongoMapper::Plugins::Associations::ManyDocumentsProxy'
    :has_many
  when 'MongoMapper::Plugins::Associations::BelongsToProxy'
    :belongs_to
  when 'MongoMapper::Plugins::Associations::OneProxy'
    :has_one
  when 'MongoMapper::Plugins::Associations::InArrayProxy'
    :has_many_in
  else
    raise NotImplementedError, "#{@association.proxy_class} not supported yet!"
  end

  send("eager_include_#{@association_type}")
end