I am currently working on a small application that will allow someone to enter strings that'll separate a larger file into smaller files.
I am having trouble getting the file to be split into the newer files. This is my code for my CSV method:
require 'csv'
new_list = []
old_list = []
def import_csv(file)
puts "Method begins"
CSV.foreach("public_schools_list.csv", :encoding => 'windows-1251:utf-8', :headers => true) do |row|
if row["company"].downcase.include?("academy" || "lutheran" || "jewish" || "private" || "christian")
CSV.open("new_list.csv", "ab") do |n|
n << row
puts "First Row"
new_list << n
end
else
CSV.open("old_list.csv", "ab") do |o|
o << row
puts "Second Row"
old_list << o
end
end
end
end
puts "New Csv: #{new_list.count}"
puts "Old Csv: #{old_list.count}"
I am just trying to check this code to see if it is splitting the files. I'm not sure if some of this is correct. There are currently only four items in the CSV list. I use the count method to check if they go into the correct files.
What code am I missing to get the main file to be separated into two?
here is my controller:
include CSVUpload
def import
csv_separate(params[:file].tempfile)
redirect_to root_url
end
then here is the module i am using:
require 'csv'
module CSVUpload
def csv_separate(file)
new_list_counter = 0
old_list_counter = 0
# puts "Method begins"
CSV.open("new_list.csv", "ab") do |new_list|
CSV.open("old_list.csv", "ab") do |old_list|
CSV.foreach(file, :encoding => 'windows-1251:utf-8', :headers => true) do |row|
if row["company"][/\b(?:academy|lutheran|jewish|private|christian)\b/i]
new_list << row
new_list_counter += 1
else
old_list << row
old_list_counter += 1
end
end
end
end
end
end
and then here is the form:
<div>
<h3>Import a CSV File</h3>
<%= form_tag({action: "import"}, multipart: true) do %>
<%= file_field_tag("file") %>
<%= submit_tag "Import CSV" %>
<% end %>
</div>
i hope that helps out a bit. Thanks!