Refractor to eliminate redundant code.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-13 10:14:40 +02:00
parent 80ac11462c
commit 5a7bdf0c57

View File

@ -25,24 +25,15 @@ use crate::habit::Habit;
pub struct HabitMgr pub struct HabitMgr
{ {
habits:Vec<Habit>, habits:Vec<Habit>,
data_dir:PathBuf, //data_dir:PathBuf,
habits_path:PathBuf,
} }
impl HabitMgr impl HabitMgr
{ {
pub fn new(data_dir:&PathBuf) -> Self pub fn new(data_dir:&PathBuf) -> Self
{ {
Self let habits_path:PathBuf = data_dir.clone().join("active_habits.json");
{
habits: Vec::new(),
data_dir: data_dir.clone(),
}
}
fn import_habits(&mut self)
{
// TODO: move habits_path to new function to avoid redundant code
let habits_path:PathBuf = self.data_dir.clone().join("active_habits.json");
if !habits_path.is_file() if !habits_path.is_file()
{ {
File::create(&habits_path) File::create(&habits_path)
@ -51,9 +42,19 @@ impl HabitMgr
habits_path.display(), e) habits_path.display(), e)
}); });
} }
let habits_file = File::open(&habits_path) Self
{
habits: Vec::new(),
//data_dir: data_dir.clone(),
habits_path,
}
}
fn import_habits(&mut self)
{
let habits_file = File::open(&self.habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", habits_path.display(), e); panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
}); });
let reader = BufReader::new(&habits_file); let reader = BufReader::new(&habits_file);
// TODO: figure out a way to do this with from_reader() instead to simplify // TODO: figure out a way to do this with from_reader() instead to simplify
@ -68,21 +69,12 @@ impl HabitMgr
pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String) pub fn add(&mut self, name:String, bad:bool, weight:u8, _days:String)
{ {
let habits_path:PathBuf = self.data_dir.clone().join("active_habits.json");
if !habits_path.is_file()
{
File::create(&habits_path)
.unwrap_or_else(|e| {
panic!("Error creating file {}:\n{}",
habits_path.display(), e)
});
}
let habits_file = OpenOptions::new() let habits_file = OpenOptions::new()
.write(true) .write(true)
.append(true) .append(true)
.open(&habits_path) .open(&self.habits_path)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
panic!("Error opening file {}:\n{}", habits_path.display(), e); panic!("Error opening file {}:\n{}", self.habits_path.display(), e);
}); });
let habit = Habit::new(name, bad, weight); let habit = Habit::new(name, bad, weight);