Last active
December 12, 2015 06:09
-
-
Save kmandreza/4727352 to your computer and use it in GitHub Desktop.
json yaml
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' | |
require 'date' | |
require 'yaml' | |
require 'json' | |
FILENAME = "people.csv" | |
NEW_FILE = "new_people.csv" | |
YAML_FILE = "people.yaml" | |
JSON_FILE = "people.json" | |
class Person | |
attr_reader :id, :first_name, :last_name, :email, :phone, :created_at | |
attr_reader :options | |
# 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 | |
def save_to_yaml | |
File.open(YAML_FILE, "wb") do |f| | |
@people.each do |person| | |
f.write(person.options.to_yaml) | |
end | |
end | |
end | |
def save_as_json | |
File.open(JSON_FILE, "wb") do |f| | |
@people.each do |person| | |
f.write(person.options.to_json) | |
end | |
end | |
end | |
end | |
parser = PersonParser.new(FILENAME) | |
new_person = { | |
"id" => 201, | |
"first_name" => "Bill", | |
"last_name" => "Hicks", | |
"email" => "[email protected]", | |
"phone" => "415-708-9256" | |
} | |
parser.add_person Person.new(new_person) | |
parser.save_to_yaml |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment