Class: Kabk::ExportHandler
- Inherits:
-
Object
- Object
- Kabk::ExportHandler
- Defined in:
- lib/kabk/export_handler.rb
Overview
Handles generating CSV or XLSX exports from a query
Class Method Summary collapse
-
.export(resource, dataset, format: "csv") ⇒ String
Binary/Text data of the exported file.
- .generate_csv(columns, records) ⇒ Object
Class Method Details
.export(resource, dataset, format: "csv") ⇒ String
Returns Binary/Text data of the exported file.
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/kabk/export_handler.rb', line 12 def self.export(resource, dataset, format: "csv") raise ApiError.new("Export format not supported", code: "VALIDATION_ERROR", http_status: 422) unless %w[csv xlsx].include?(format) # We fetch all records for the export query (ignoring pagination limits usually, or applying large limit) # For now, buffer everything in memory as requested. records = dataset.all hydrated_records = RelationHydrator.hydrate(resource, records) columns = resource.fields.map { |f| f.name.to_s } display_columns = resource.fields.select { |f| f.type == "relation" && f.relation }.map do |f| rel = f.relation (rel["display_key"] || rel[:display_key] || "#{f.name}_display").to_s end all_columns = columns + display_columns if format == "csv" generate_csv(all_columns, hydrated_records) else # Stub for XLSX - requires external gem like caxlsx. We just return CSV for now as a fallback # or raise an error asking to install caxlsx. generate_csv(all_columns, hydrated_records) end end |
.generate_csv(columns, records) ⇒ Object
39 40 41 42 43 44 45 46 |
# File 'lib/kabk/export_handler.rb', line 39 def self.generate_csv(columns, records) CSV.generate do |csv| csv << columns records.each do |record| csv << columns.map { |col| record[col.to_sym] || record[col] } end end end |