I am working on an app that parses various forms of spreadsheets. It worked for CSV and now I am trying to extend it to XLS, XLSX, ODS and Google Spreadsheets using the roo gem.
I want the uploaded file to be parsed correctly depending on the file name. I have tried to accomplish this with regex and switch and if statements but so far it did not work. The problem seems to within the condition with the regex because even CSV files are not parsed anymore.
Here is my current version:
def create
@deck = Deck.new
@deck.name = params[:uploadform][:name]
@deckmsg = ""
if @deck.save
@deckmsg='Deck was successfully created.'
else
respond_to do |format|
format.html { render action: "new", notice: 'Deck was not created.' }
end
end
if params[:uploadform][:file] =~ /.*(csv)$/
begin
@answers = Array.new
@questions = Array.new
CSV.parse(params[:uploadform][:file].read) do |row|
If I take the if statement out it works so the problem has to be in there. I’m using a normal upload form.
Perhaps the CSV file you uploaded has a capitalized extension?
myfile.CSVwould not be matched by your regex. You can remedy this by telling it to match case-insensitive:I’ve also removed the extraneous parenthesis and added in an explicit
.so thatmycsvdoesn’t get matched. You don’t need to match all the characters before the extension, either (but probably want to ensure there’s at least one so the file isn’t just named “.csv”).Further, it’s likely that
params[:uploadform][:file]isn’t a string like you expect. It’s probably anActiveDispatch::UploadedFile, in which case you will have to calloriginal_filenameon it to get the filename: