Class: DataExport::Exporter
- Inherits:
-
Object
- Object
- DataExport::Exporter
- Defined in:
- lib/export_data.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.
- .export_to_text(objects, file_path) ⇒ Object
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/export_data.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 |
.export_to_text(objects, file_path) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/export_data.rb', line 49 def self.export_to_text(objects, file_path) begin File.open(file_path, 'w') do |file| if objects.empty? puts 'No objects to export.' # Or handle this case as needed return end # Write the object's attribute values as text lines objects.each do |obj| file.puts(obj.attributes.values.join("\t")) # Use '\t' as a delimiter for tab-separated values end end rescue Errno::ENOENT => e puts "An error occurred while exporting to text: #{e.message}" end end |