Skip to content

Instantly share code, notes, and snippets.

@jonny-gates
Created January 24, 2020 19:34
Show Gist options
  • Save jonny-gates/7d3430216941645472f3793f7c4bb638 to your computer and use it in GitHub Desktop.
Save jonny-gates/7d3430216941645472f3793f7c4bb638 to your computer and use it in GitHub Desktop.
Cookbook Recap
require_relative 'view'
require_relative 'recipe'
class Controller
def initialize(cookbook)
@cookbook = cookbook
@view = View.new
end
def list
# Get the recipes (cookbook)
recipes = @cookbook.all
# p recipes = [<object Recipe>, <object Recipe>]
# Display the recipes (view)
@view.list_recipes(recipes)
end
def create
# Ask the user the recipe name (view)
name = @view.ask_user_for('name')
# Ask the user the recipe description (view)
description = @view.ask_user_for('description')
# Create a recipe instance (model)
recipe = Recipe.new(name, description)
# Add to the cookbook (repo/db)
@cookbook.add_recipe(recipe)
end
end
require 'csv'
require_relative 'recipe'
class Cookbook
def initialize(csv_path)
@csv_path = csv_path
@recipes = []
load_csv
end
def all
@recipes
end
def add_recipe(recipe)
p recipe
@recipes << recipe
save_csv
end
def remove_recipe(recipe_index)
end
private
def save_csv
CSV.open(@csv_path, 'wb') do |csv|
@recipes.each do |recipe|
csv << [recipe.name, recipe.description]
end
end
end
def load_csv
CSV.foreach(@csv_path) do |row|
@recipes << Recipe.new(row[0], row[1])
end
end
end
class Recipe
attr_reader :name, :description
def initialize(name, description)
@name = name
@description = description
end
end
# Model - Recipe - Representation of our data
# Repository - Cookbook - DB
# View - View - Interacting with the user
# Controller - Controller - Coordinates the other components. The brain.
# Router - Router - Tells the controller which action to do
class View
def list_recipes(recipes)
recipes.each_with_index do |recipe, index|
puts "#{index + 1}. #{recipe.name}"
end
end
def ask_user_for(attribute)
puts "What is the #{attribute}"
return gets.chomp
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment