Last active
August 29, 2015 13:59
-
-
Save MilanGrubnic70/10593434 to your computer and use it in GitHub Desktop.
CSV: Parsing and updating/appending.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
#creates headers as symbols from top row data | |
def people | |
return @people if @people # If we've already parsed the CSV file, don't parse it again. It's nil so it parses. | |
@people = [] # Remember: @people is +nil+ by default. So turn it into an Array. | |
CSV.foreach(@file, :headers => true, :header_converters => :symbol) do |row| | |
@people << Person.new(row[:id], row[:first_name], row[:last_name], row[:email], row[:phone], row[:created_at]) | |
end # do | |
@people | |
# We've never called people before, now parse the CSV file | |
# and return an Array of Person objects here. Save the | |
# Array in the @people instance variable. | |
end #people | |
#appends to file: | |
def save_to_cvs_file | |
CSV.open(@file, "a+") do |csv| | |
csv << ["#{@people.last.id}", "#{@people.last.first_name}", "#{@people.last.last_name}", "#{@people.last.email}", "#{@people.last.phone}", "#{@people.last.created_at}"] | |
end #do | |
end #save to cvs file | |
#rewrites the whole csv file: | |
def save | |
CSV.open(@file, 'w') do |file| | |
file << ["id", "first_name", "last_name", "email", "phone", "created_at"] | |
@people.each { |row| file << [row.id, row.first_name, row.last_name, row.email, row.phone, row.created_at] } | |
end | |
puts "#{@file} has been saved!" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment