Created
February 7, 2013 02:01
-
-
Save alyraz/4727782 to your computer and use it in GitHub Desktop.
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
class Person | |
attr_reader :id, :first_name, :last_name, :email, :phone, :created_at | |
def initialize(id, first_name, last_name, email, phone, created_at) | |
@id = id | |
@first_name = first_name | |
@last_name = last_name | |
@email = email | |
@phone = phone | |
@created_at = DateTime.parse(created_at) | |
end | |
end | |
class PersonParser | |
attr_reader :file, :people | |
def initialize(file) | |
@file = file | |
@people = [] | |
end | |
def people | |
return @people unless @people.empty? | |
file_parse | |
@people | |
end | |
def file_parse | |
counter = 0 | |
CSV.foreach("file.csv", headers: true) do |row| | |
# if counter == 0 | |
# @header = row | |
# else | |
@people << Person.new(row["id"], | |
row["first_name"], | |
row["last_name"], | |
row["email"], | |
row["phone"], | |
row["created_at"]) | |
# end | |
counter += 1 | |
end | |
end | |
def add_person(person) | |
@people << person | |
end | |
def save | |
CSV.open("file.csv", "w") do |csv| | |
@people.each do |person| | |
csv << [ person.id, | |
person.first_name, | |
person.last_name, | |
person.email, | |
person.phone, | |
person.created_at] | |
end | |
end | |
end | |
end | |
#Driver Code | |
require 'csv' | |
require 'pp' | |
require 'date' | |
parser = PersonParser.new('file.csv') | |
puts "There are #{parser.people.size} people in the file '#{parser.file}'." | |
parser.file_parse | |
PP.pp parser.people | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment