Module: SeedDump::DumpMethods

Includes:
Enumeration
Included in:
SeedDump
Defined in:
lib/seed_dump/dump_methods.rb,
lib/seed_dump/dump_methods/enumeration.rb

Overview

Provides the core logic for dumping records.

Defined Under Namespace

Modules: Enumeration

Instance Method Summary collapse

Methods included from Enumeration

#active_record_enumeration, #batch_params_from, #batch_size_from, #enumerable_enumeration

Instance Method Details

#dump(records, options = {}) ⇒ String?

Dumps a collection of records to a string or file.

Parameters:

  • records (ActiveRecord::Relation, Class, Array<ActiveRecord::Base>)

    The records to dump.

  • options (Hash) (defaults to: {})

    Options for dumping.

Options Hash (options):

  • :file (String)

    Path to the output file. If nil, returns a string.

  • :append (Boolean)

    Append to the file instead of overwriting. Default: false.

  • :batch_size (Integer)

    Number of records per batch. Default: 1000.

  • :exclude (Array<Symbol>)

    Attributes to exclude. Default: [:id, :created_at, :updated_at, :created_on, :updated_on].

  • :import (Boolean, Hash)

    Use activerecord-import format. If Hash, passed as options to import. Default: false.

  • :insert_all (Boolean)

    Use Rails 6+ insert_all format for faster bulk inserts. Default: false.

  • :upsert_all (Boolean)

    Use Rails 6+ upsert_all format to preserve IDs and fix foreign key issues (issue #104). Default: false.

  • :group_sti_by_class (Boolean)

    Group STI records by their actual class instead of base_class (issue #170). Default: false.

Returns:

  • (String, nil)

    The dump string if :file is nil, otherwise nil.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/seed_dump/dump_methods.rb', line 27

def dump(records, options = {})
  # Handle potential empty input gracefully
  # Use unscope(:select) for AR relations to avoid issues with default_scope
  # that selects specific columns, which would cause COUNT(col1, col2, ...) errors
  record_count = if records.respond_to?(:unscope)
                   records.unscope(:select).count
                 elsif records.respond_to?(:count)
                   records.count
                 elsif records.respond_to?(:empty?)
                   records.empty? ? 0 : 1
                 else
                   records.size
                 end
  return nil if record_count == 0

  io = nil
  begin
    io = open_io(options)
    write_records_to_io(records, io, options)

    # If no file option was given (meaning we used StringIO), read the content
    if options[:file].blank? # Check if :file option is nil or empty
      io.rewind
      io.read
    else
      # If a file option was given, return nil as the file was written directly
      nil
    end
  ensure
    # Ensure the IO object is closed if it's a File object
    io.close if io.is_a?(File) && io.respond_to?(:close) && !io.closed?
  end
end