views:

36

answers:

3

I am new to Rails. In my project where users have to upload a file, I store it then I have to parse the file contents and show it in new form.

I have successfully done the file uploading portion, now how should I read the contents of it?

+2  A: 

You can open files and read their contents in Ruby using the File class, as this simple example demonstrates:

# Open a file in read-only mode and print each line to the console
file = File.open('afile.txt', 'r') do |f|
  f.each do |line|
    puts line
  end
end
John Topley
Please make sure to close the file after you use it, or, even better, use the block-form of `File.open` which does so automatically.
sepp2k
@sepp2k Good point, I've updated my example.
John Topley
+1  A: 

Try something like this:

upload = params[:your_upload_form_element]
content = upload.is_a?(StringIO) ? upload.read : File.read(upload.local_path)

Very small files can be passed as strings instead of uploaded files, therefore you should check for that and handle it accordingly.

Lars Haugseth
A: 

thanks guys ......... i got it workin

akhil