Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created February 7, 2013 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmandreza/4727162 to your computer and use it in GitHub Desktop.
Save kmandreza/4727162 to your computer and use it in GitHub Desktop.
CSV In, CSV Out
require 'csv'
require 'date'
FILENAME = "people.csv"
NEW_FILE = "new_people.csv"
class Person
attr_reader :id, :first_name, :last_name, :email, :phone, :created_at
# id,first_name,last_name,email,phone,created_at
def initialize(person_info)
default_options = {
"created_at" => DateTime.now
}
options = person_info.merge(default_options)
@id = options["id"]
@first_name = options["first_name"]
@last_name = options["last_name"]
@email = options["email"]
@phone = options["phone"]
@created_at = options["created_at"]
end
def to_array
[@id, @first_name, @last_name, @email, @phone, @created_at]
end
end
class PersonParser
def initialize(filename)
@people = []
CSV.foreach(filename, :headers => :first_row) do |row|
@people << Person.new(row.to_hash)
end
end
def people
@people
end
# person_parse.add_person({:id => 2, :first_name => "Abi"})
def add_person(new_person)
@people << new_person
end
def save
CSV.open(NEW_FILE, "wb", :headers => :first_row) do |csv|
@people.each do |person|
csv << person.to_array
end
end
end
end
parser = PersonParser.new(FILENAME)
puts parser.people
new_person = {
"id" => 201,
"first_name" => "Bill",
"last_name" => "Hicks",
"email" => "bh@gmail.com",
"phone" => "415-708-9256"
}
parser.add_person Person.new(new_person)
parser.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment