extern crate cookbook; extern crate diesel; use std::io::{stdin}; use diesel::SqliteConnection; use cookbook::*; use cookbook::recipes::{NewRecipe, RecipeCategory}; use cookbook::ingredients::{IngredientList}; struct CreateRecipe<'a> { connection: &'a SqliteConnection, title: &'a str, category: Option, ingredients: IngredientList, } impl<'a> CreateRecipe<'a> { fn new(conn: &'a SqliteConnection) -> Self { CreateRecipe{ connection: conn, title: "New recipe", category: None, ingredients: IngredientList::new(), } } fn set_title(&mut self, title: &'a str) { self.title = title; } fn set_category(&mut self, id: i16) { self.category = RecipeCategory::from_id(id); } fn add_ingredient(&mut self, name: String) { use crate::ingredients::*; let name = name.trim(); // Check it exists or create match get_id_or_create(self.connection, &name) { Ok(id) => { println!("Got id {}", id); self.ingredients.push(id); }, Err(_) => println!("Error adding ingredient") } } /// Builds a NewRecipe instance from current data and insert it. fn insert(self) { let new_recipe = NewRecipe { title: self.title, category: self.category.unwrap_or(RecipeCategory::Breakfast), ingredients: self.ingredients, preparation: "" }; match new_recipe.insert(self.connection) { Ok(new) => println!("Added {}", new.title), Err(e) => println!("Error: {}", e), }; } } fn main() { let conn = establish_connection(); let mut builder = CreateRecipe::new(&conn); println!("Title : "); let mut title = String::new(); stdin().read_line(&mut title).unwrap(); let title = &title[..(title.len() - 1)]; builder.set_title(title); println!("Category : "); for cat in &RecipeCategory::all() { println!("{} - {}", cat.id(), cat.name()); } let mut category_id = String::new(); stdin().read_line(&mut category_id).unwrap(); let category_id = category_id.trim().parse::().unwrap_or(0); builder.set_category(category_id); println!("Ingredients (empty line to finish): "); loop { let mut ingdts = String::new(); stdin().read_line(&mut ingdts).unwrap(); if &ingdts == "\r\n" { break; } builder.add_ingredient(ingdts); } builder.insert(); } #[cfg(not(windows))] const EOF: &'static str = "CTRL+D"; #[cfg(windows)] const EOF: &'static str = "CTRL+Z";