| Class | Populator::Factory |
| In: |
lib/populator/factory.rb
|
| Parent: | Object |
Builds multiple Populator::Record instances and saves them to the database
| DEFAULT_RECORDS_PER_QUERY | = | 1000 |
Fetches the factory dedicated to a given model class. You should always use this method instead of instatiating a factory directly so that a single factory is shared on multiple calls.
# File lib/populator/factory.rb, line 12
12: def self.for_model(model_class)
13: @factories[model_class] ||= new(model_class)
14: end
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.
# File lib/populator/factory.rb, line 27
27: def self.remember_depth
28: @depth += 1
29: yield
30: @depth -= 1
31: save_remaining_records if @depth.zero?
32: end
Find all remaining factories and call save_records on them.
# File lib/populator/factory.rb, line 17
17: def self.save_remaining_records
18: @factories.values.each do |factory|
19: factory.save_records
20: end
21: @factories = {}
22: end
Builds multiple Populator::Record instances and calls save_records them when :per_query limit option is reached.
# File lib/populator/factory.rb, line 49
49: def build_records(amount, per_query, &block)
50: amount.times do
51: record = Record.new(@model_class, last_id_in_database + @records.size + 1)
52: @records << record
53: block.call(record) if block
54: save_records if @records.size >= per_query
55: end
56: end
Entry method for building records. Delegates to build_records after remember_depth.
# File lib/populator/factory.rb, line 41
41: def populate(amount, options = {}, &block)
42: self.class.remember_depth do
43: build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block)
44: end
45: end
Saves the records to the database by calling populate on the current database adapter.
# File lib/populator/factory.rb, line 59
59: def save_records
60: unless @records.empty?
61: @model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate")
62: @last_id_in_database = @records.last.id
63: @records.clear
64: end
65: end