Class: MongoPopulator::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_populator/factory.rb

Overview

Builds multiple Populator::Record instances and saves them to the database

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ Factory

Use for_collection instead of instatiating a record directly.



34
35
36
37
# File 'lib/mongo_populator/factory.rb', line 34

def initialize(collection)
  @collection = collection
  @records = []
end

Class Method Details

.for_collection(collection) ⇒ Object

Fetches the factory dedicated to a given collection. You should always use this method instead of instatiating a factory directly so that a single factory is shared on multiple calls.



11
12
13
# File 'lib/mongo_populator/factory.rb', line 11

def self.for_collection(collection)
  @factories[collection] ||= new(collection)
end

.remember_depthObject

Keep track of nested factory calls so we can save the remaining records once we are done with the base factory. This makes Populator more efficient when nesting factories.



26
27
28
29
30
31
# File 'lib/mongo_populator/factory.rb', line 26

def self.remember_depth
  @depth += 1
  yield
  @depth -= 1
  save_remaining_records if @depth.zero?
end

.save_remaining_recordsObject

Find all remaining factories and call save_records on them.



16
17
18
19
20
21
# File 'lib/mongo_populator/factory.rb', line 16

def self.save_remaining_records
  @factories.values.each do |factory|
    factory.save_records
  end
  @factories = {}
end

Instance Method Details

#build_records(amount, &block) ⇒ Object

Builds multiple MongoPopulator::Record instances and calls save_records them when :per_query limit option is reached.



48
49
50
51
52
53
54
55
56
# File 'lib/mongo_populator/factory.rb', line 48

def build_records(amount, &block)
  amount.times do
    # index = last_id_in_database + @records.size + 1
    record = Record.new(@collection)
    block.call(record) if block
    @records << record.attributes.delete_if {|k,v| v.is_a?(MongoSkip) }
    save_records 
  end
end

#populate(amount, &block) ⇒ Object

Entry method for building records. Delegates to build_records after remember_depth.



40
41
42
43
44
# File 'lib/mongo_populator/factory.rb', line 40

def populate(amount, &block)
  self.class.remember_depth do
    build_records(MongoPopulator.interpret_value(amount), &block)
  end
end

#save_recordsObject

Saves the records to the database



59
60
61
62
63
64
65
# File 'lib/mongo_populator/factory.rb', line 59

def save_records
  @records.each do |record|
    @collection.insert(record)
  end
  # @last_id_in_database = @records.last[:_id]
  @records.clear
end