Files
CookAssistant/cookbook/src/bin/write_recipe.rs
2019-02-02 15:56:44 +01:00

101 lines
2.5 KiB
Rust

extern crate cookbook;
extern crate diesel;
use std::io::{Read, stdin};
use diesel::SqliteConnection;
use self::cookbook::*;
use self::models::{NewRecipe, fields::RecipeCategory};
struct CreateRecipe<'a> {
connection: &'a SqliteConnection,
title: &'a str,
category: Option<RecipeCategory>,
ingredients: String,
}
impl<'a> CreateRecipe<'a> {
fn new(conn: &'a SqliteConnection) -> Self {
CreateRecipe{
connection: conn,
title: "New recipe",
category: None,
ingredients: String::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::*;
// Check it exists or create
if let Some(_ingdt) = find(self.connection, &name) {
println!("=");
} else {
create(self.connection, &name);
println!("+{}", &name);
}
self.ingredients.push_str(&name);
}
/// Builds a NewRecipe instance from current data and insert it.
fn insert(self) {
let new_recipe = NewRecipe::new(
self.title,
self.category.unwrap_or(RecipeCategory::Breakfast),
&self.ingredients,
"");
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::<i16>().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";