generated from OBJNULL/Dockerized-Rust
Created CSV Writer Tool
This commit is contained in:
parent
78744a104f
commit
6173c83da5
1 changed files with 59 additions and 0 deletions
59
project/src/writer.rs
Normal file
59
project/src/writer.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
// Libraries
|
||||
use super::action::Transaction;
|
||||
|
||||
use std::io::Result;
|
||||
|
||||
use csv;
|
||||
|
||||
// Structures
|
||||
pub struct Writer {
|
||||
transactions: Vec<Transaction>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
// Implementations
|
||||
impl Writer {
|
||||
// Constructors
|
||||
pub fn new(transactions: &Vec<Transaction>, path: String) -> Self {
|
||||
// Creating own list of transactions
|
||||
let mut self_transactions: Vec<Transaction> = Vec::new();
|
||||
for transaction in transactions {
|
||||
self_transactions.push(Transaction {
|
||||
description: transaction.description.clone(),
|
||||
amount: transaction.amount.clone(),
|
||||
date: transaction.date.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
// Returning result
|
||||
Self {
|
||||
transactions: self_transactions,
|
||||
path,
|
||||
}
|
||||
}
|
||||
|
||||
// Functions
|
||||
pub fn save(&self) -> Result<()> {
|
||||
// Creating a file based on path
|
||||
let mut writer = csv::Writer::from_path(&self.path)?;
|
||||
|
||||
// Creating the Header
|
||||
writer.write_record(&["Date", "Description", "Amount"])?;
|
||||
|
||||
// Writing all transactions
|
||||
for transaction in &self.transactions {
|
||||
// Creating a record
|
||||
writer.write_record(&[
|
||||
transaction.date.clone(),
|
||||
transaction.description.clone(),
|
||||
transaction.amount.clone().to_string(),
|
||||
])?;
|
||||
}
|
||||
|
||||
// Flush writer
|
||||
writer.flush()?;
|
||||
|
||||
// Ok!!
|
||||
Ok(())
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue