File Upload in Ruby…so stupidly simple

28 08 2007

On a form:
<%= form_tag({:action=>:save_csv_file}, :multipart => true)%>
<input name="csv_file" type="file">
<%= submit_tag "upload it" %>
<%=end_form_tag%>

Then in the controller:
@name=UserLogs.new #Store the filename in my db
@file=params['csv_file'] # get the file from the form (its called 'csv_file')
if @file.original_filename.index(".csv") #this checks the filename
#in this case its a CSV file

I add a time stamp to the file name:
@filename=@file.original_filename.chomp(".csv")+"_"+Time.now.strftime('%m-%d-%Y_%H_%M_%S')

Next is the where you chose the directory, “wb” is so Windows doesn’t fumble a binary file: File.open("#{RAILS_ROOT}/public/upload/#{@filename}.csv", "wb") do |f|
#This writes to the opened space above:
f.write(params['csv_file'].read)
end

Below saves the filename to the db so I can link to the filename later:
@name.filename=@filename+".csv"
@name.kind="csv_upload"
@name.save

Now you have a user uploaded file stored to the filesystem with its name and type stored in the db.





Ruby Console to the Rescue

28 08 2007

I hadn’t used Ruby console ever to test things out. That means lots of code tweaking and page refreshes to test things…not a good approach I know.

So I figured I’d fire up the console

$ cd /MyRails/AppDirectory/
$ ruby script/console

So from there I was able to test all kinds of silly stuff.  Like how to remove non digit characters from a string and leave only a number. I was able to test several different ways and it instantly tells me if my syntax is wrong and its quick and easy to fix a missing comma or something like that.

It was also very helpful testing out the GeoKit plugin for mapping and GeoCoding addresses.  After only 10 minutes instead of like an hour I was able to work out the syntax and get the thing working, w00t.

And this morning I needed to figure out how to combine a date and time from two separate user fields into one field stored in my silly silly MS SQL database.  And I did it in about 2 minutes instead of the normal 20 or so of fooling in my code and refreshing the page and building test pieces and then backing out the test pieces and getting distracted with another problem on the page and fumbling with syntax for 10 page reloads and and and….

All in all Ruby console to the rescue.