How to parse the contents of a downloaded file in RoR

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

I have successfully downloaded the file, now how should I read its contents?

+3
source share
3 answers

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 transferred as strings instead of downloaded files, so you should check this and process it accordingly.

+5
source

You can open files and read their contents in Ruby with File , 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
+2

, , , . , .

routes.rb

resources :contacts do 
  collection do
    get 'import/new', to: :new_import  # import_new_contacts_path

    post :import, on: :collection      # import_contacts_path
  end
end

//new_import.html.erb

<%= form_for @contacts, url: import_contacts_path, html: { multipart: true } do |f| %>

  <%= f.file_field :import_file %>

<% end %>

Controllers / contacts _controller.rb

def new_import
end

def import
  begin
    Contact.import( params[:contacts][:import_file] ) 

    flash[:success] = "<strong>Contacts Imported!</strong>"

    redirect_to contacts_path

  rescue => exception 
    flash[:error] = "There was a problem importing that contacts file.<br>
      <strong>#{exception.message}</strong><br>"

    redirect_to import_new_contacts_path
  end
end

Contact Model

/contact.rb models

def import import_file 
  File.foreach( import_file.path ).with_index do |line, index| 

    # Process each line.

    # For any errors just raise an error with a message like this: 
    #   raise "There is a duplicate in row #{index + 1}."
    # And your controller will redirect the user and show a flash message.

  end
end

Hope this helps others!

In JP

0
source

Source: https://habr.com/ru/post/1754192/


All Articles