Module: SeedDump::DumpMethods::Enumeration
- Included in:
- SeedDump::DumpMethods
- Defined in:
- lib/seed_dump/dump_methods/enumeration.rb
Instance Method Summary collapse
- #active_record_enumeration(records, io, options) ⇒ Object
- #batch_params_from(records, options) ⇒ Object
- #batch_size_from(records, options) ⇒ Object
- #enumerable_enumeration(records, io, options) ⇒ Object
Instance Method Details
#active_record_enumeration(records, io, options) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/seed_dump/dump_methods/enumeration.rb', line 4 def active_record_enumeration(records, io, ) # If the records don't already have an order, # order them by primary key ascending (if the table has a primary key). if !records.respond_to?(:arel) || records.arel.orders.blank? if records.primary_key.present? records = records.order(records.primary_key => :asc) end end num_of_batches, batch_size, last_batch_size = batch_params_from(records, ) # Loop through each batch (1..num_of_batches).each do |batch_number| record_strings = [] last_batch = (batch_number == num_of_batches) cur_batch_size = if last_batch last_batch_size else batch_size end # Loop through the records of the current batch records.offset((batch_number - 1) * batch_size).limit(cur_batch_size).each do |record| record_strings << dump_record(record, ) end yield record_strings, last_batch end end |
#batch_params_from(records, options) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/seed_dump/dump_methods/enumeration.rb', line 58 def batch_params_from(records, ) batch_size = batch_size_from(records, ) # Use unscope(:select) to avoid issues with default_scope that selects # specific columns, which would cause COUNT(col1, col2, ...) errors count = if records.respond_to?(:unscope) records.unscope(:select).count else records.count end remainder = count % batch_size [((count.to_f / batch_size).ceil), batch_size, (remainder == 0 ? batch_size : remainder)] end |
#batch_size_from(records, options) ⇒ Object
74 75 76 77 78 79 80 |
# File 'lib/seed_dump/dump_methods/enumeration.rb', line 74 def batch_size_from(records, ) if [:batch_size].present? [:batch_size].to_i else 1000 end end |
#enumerable_enumeration(records, io, options) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/seed_dump/dump_methods/enumeration.rb', line 37 def enumerable_enumeration(records, io, ) num_of_batches, batch_size = batch_params_from(records, ) record_strings = [] batch_number = 1 records.each_with_index do |record, i| record_strings << dump_record(record, ) last_batch = (i == records.length - 1) if (record_strings.length == batch_size) || last_batch yield record_strings, last_batch record_strings = [] batch_number += 1 end end end |