0

I'm producing a CSV export (in ruby, from rails) of a variable number of records. The number of fields exported per record varies depending on how many authors each book has. This isn't ideal, given that the users are going to look at this CSV in something like Excel, and expect to see the data presented consistently in columns. How can I set the number of columns to be the total number of times the block gets iterated, given that the structure of the csv builder is something like this:

# header-row for the data
csv << ["column heading 1", "column heading 2", "column heading 3" #etc]

Book.all do |book|
  row_data = book.id
  row_data << book.some_other_field # etc
  book.authors.each do |author|
    row_data << author.first.name 
    #etc
snowangel
  • 3,452
  • 3
  • 29
  • 72

1 Answers1

1

Update: Stupid me misread the question.

I would simply delay writing the header for some time. Ruby has the ability to pre-pend data into a file: Prepend a single line to file with Ruby

You just need to carry around the max length of your authors:

max_authors = 0    
Book.all do |book|
  row_data = book.id
  row_data << book.some_other_field # etc
  if book.authors.count > max_authors 
    max_authors = book.authors.count
  end
  book.authors.each do |author|
    row_data << author.first.name 
    #etc

# header-row for the data
a = (0..max_authors).collect { |n| "column heading #{n}" }
csv << a.join(",") #obviously this has to be prepended

I hope the code works.. Couldn't test it .. but you get the idea

Community
  • 1
  • 1
Tigraine
  • 23,358
  • 11
  • 65
  • 110