Skip to content

Instantly share code, notes, and snippets.

@matoni109
Created November 3, 2020 10:18
Show Gist options
  • Save matoni109/d69dbba22cd0a1467da05e8406039187 to your computer and use it in GitHub Desktop.
Save matoni109/d69dbba22cd0a1467da05e8406039187 to your computer and use it in GitHub Desktop.
require 'csv'
require_relative '../models/meal'
require "pry-byebug"
# ../../data
class MealRepository
# ID and NAME and CURED and ROOM_ID
def initialize(csv_file)
@csv = csv_file
@meals = []
@next_id = 1
load_csv if File.exist?(csv_file)
end
def create(meal)
meal.id = @next_id
@next_id += 1
@meals << meal
save_csv
end
def all
@meals
end
def find(id)
# Todo: return the room with the spec ID
# @ .find { |artist | arist.id == id }
end
private
def load_csv
# ID name price
@next_id = 0
csv_options = { headers: :first_row, header_converters: :symbol }
CSV.foreach(@csv, csv_options) do |row|
row[:id] = row[:id].to_i # Convert column to Integer
# row[:cured] = row[:cured] == "true"
# row[:name]
row[:price] = row[:price].to_i
# Convert column to boolean
@meals << Meal.new(row)
@next_id = row[:id]
end
@next_id += 1
end
def save_csv
#meals = []
# binding.pry
CSV.open(@csv, 'wb') do |row|
row << %w(id, name, price)
@meals.each do |meal|
# binding.pry
row << [meal.id, meal.name, meal.price]
end
end
end
end
# my_meal = Meal.new(name: "scones", price: 5)
# my_meal_repo = MealRepository.new('../../data/meals.csv')
# p my_meal_repo.create(my_meal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment