I am reading a CSV file from a CDN and adding data to it then writing it back to a CDN for this reason I can't use append file.
I am also reordering the file which is why I have to turn it back into a CSV::Table
This code is a slimed down version of what I have but the problem is still replicated.
class SomeForm::Form
class << self
def add
data = CSV.parse(open(csv_file_url).read, headers: true)
data << ['david', 'smith'] # this will be dynamic
# data = data.sort_by { |row| [row['Firstname'], row['Lastname']] }
write_csv_file(CSV::Table.new(data).to_csv)
end
def csv_file_url
#somecode to get the file_url
end
def write_csv_file(data)
#somecode to write the file to the cdn
end
end
end
CSV file
Firstname,Lastname
So if I run SomeForm::Form.add with the csv file as above it outputs (removing the headers)
,
David,smith
However if the CSV file has at least one record in eg
Firstname,Lastname
Steve,Cougan
and run the code it adds the new record as expected
Firstname,Lastname
Steve,Cougan
david,smith
I would like to get this to work with csv with data in and csv with just the headers in.
As a aside this is for a rails3 project, though the above is replicatable in rails 5 as well
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire