Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created July 11, 2017 22:02
Show Gist options
  • Save oddlyfunctional/b33156ba490f326efec301a35c2059ad to your computer and use it in GitHub Desktop.
Save oddlyfunctional/b33156ba490f326efec301a35c2059ad to your computer and use it in GitHub Desktop.
require 'csv'
require_relative '../models/customer'
class CustomerRepository
def initialize(csv_path)
@csv_path = csv_path
@customers = []
load_csv if File.exist?(@csv_path)
@next_id = @customers.empty? ? 1 : @customers.last.id + 1
end
def all
@customers
end
def add(customer)
customer.id = @next_id
@customers << customer
save_csv
@next_id += 1
end
private
def load_csv
options = { headers: :first_row, header_converters: :symbol }
CSV.foreach(@csv_path, options) do |row|
row[:id] = row[:id].to_i
@customers << Customer.new(row)
end
end
def save_csv
CSV.open(@csv_path, "wb") do |csv|
csv << ["id", "name", "address"]
@customers.each do |customer|
csv << [customer.id, customer.name, customer.address]
end
end
end
end
require 'csv'
require_relative '../models/meal'
class MealRepository
def initialize(csv_path)
@csv_path = csv_path
@meals = []
load_csv if File.exist?(@csv_path)
@next_id = @meals.empty? ? 1 : @meals.last.id + 1
end
def all
@meals
end
def add(meal)
meal.id = @next_id
@meals << meal
save_csv
@next_id += 1
end
private
def load_csv
options = { headers: :first_row, header_converters: :symbol }
CSV.foreach(@csv_path, options) do |row|
row[:id] = row[:id].to_i
row[:price] = row[:price].to_i
@meals << Meal.new(row)
end
end
def save_csv
CSV.open(@csv_path, "wb") do |csv|
csv << ["id", "name", "price"]
@meals.each do |meal|
csv << [meal.id, meal.name, meal.price]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment