Class: DataExport::Exporter

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

Overview

Exporter class for handling data exports to CSV

Class Method Summary collapse

Class Method Details

.export_to_csv(objects, file_path) ⇒ void

This method returns an undefined value.

Exports data to a CSV file.

This method takes an array of objects and exports them to a CSV file specified by the ‘file_path`. It expects that the first object in the array defines the column names for the CSV file.

Examples:

Export user data to CSV:

objects = [user1, user2]
DataExport::Exporter.export_to_csv(objects, 'users.csv')

Parameters:

  • objects (Array)

    The objects to export to CSV.

  • file_path (String)

    The path to the CSV file to be created.



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

def self.export_to_csv(objects, file_path)
  begin
    CSV.open(file_path, 'w') do |csv|
      if objects.empty?
        puts 'No objects to export.' # Or handle this case as needed
        return
      end
      
      # Write the header row using the first object's attributes
      csv << objects.first.attributes.keys
      
      # Write the object's attribute values as data rows
      objects.each do |obj|
        csv << obj.attributes.values
      end
    end
  rescue CSV::MalformedCSVError => e
    puts "An error occurred while exporting to CSV: #{e.message}"
  rescue Errno::ENOENT => e
    puts "An error occurred while exporting to CSV: #{e.message}"
  end
end