Class: DataExport::Exporter
- Inherits:
-
Object
- Object
- DataExport::Exporter
- Defined in:
- lib/data_export.rb
Overview
Exporter class for handling data exports to CSV
Class Method Summary collapse
-
.export_to_csv(objects, file_path) ⇒ void
Exports data to a CSV file.
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.
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.}" rescue Errno::ENOENT => e puts "An error occurred while exporting to CSV: #{e.}" end end |