Skip to content

Commit

Permalink
Add tail option for expandedDisplay
Browse files Browse the repository at this point in the history
Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>
  • Loading branch information
zhiburt committed Sep 10, 2021
1 parent 35f56e3 commit 8177826
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
14 changes: 11 additions & 3 deletions src/display/expanded_display.rs
Expand Up @@ -46,13 +46,21 @@ impl ExpandedDisplay {

/// Sets max width of value.
/// The rest will be trunceted.
pub fn truncate(&mut self, max: usize) -> &mut Self {
pub fn truncate(&mut self, max: usize, tail: impl AsRef<str>) -> &mut Self {
let tail = tail.as_ref().to_string();
self.format_value = Some(Box::new(move |s| {
s.chars()
let mut s = s
.chars()
.take(max)
.collect::<String>()
.escape_debug()
.to_string()
.to_string();

if s.chars().count() >= max {
s.push_str(&tail);
}

s
}));
self
}
Expand Down
49 changes: 48 additions & 1 deletion tests/expanded_display_test.rs
Expand Up @@ -323,7 +323,54 @@ fn display_with_truncate() {
"link | htt\n",
);

let table = ExpandedDisplay::new(&data).truncate(3).to_string();
let table = ExpandedDisplay::new(&data).truncate(3, "").to_string();

assert_eq!(table, expected);
}

#[test]
fn display_with_truncate_with_tail() {
#[derive(Tabled)]
struct Linux {
id: u8,
destribution: &'static str,
link: &'static str,
}

let data = vec![
Linux {
id: 0,
destribution: "Fedora",
link: "https://getfedora.org/",
},
Linux {
id: 2,
destribution: "OpenSUSE",
link: "https://www.opensuse.org/",
},
Linux {
id: 3,
destribution: "Endeavouros",
link: "https://endeavouros.com/",
},
];

let expected = concat!(
"-[ RECORD 0 ]--------\n",
"id | 0\n",
"destribution | Fed...\n",
"link | htt...\n",
"-[ RECORD 1 ]--------\n",
"id | 2\n",
"destribution | Ope...\n",
"link | htt...\n",
"-[ RECORD 2 ]--------\n",
"id | 3\n",
"destribution | End...\n",
"link | htt...\n",
);

let table = ExpandedDisplay::new(&data).truncate(3, "...").to_string();

assert_eq!(table, expected);
}
Expand Down

0 comments on commit 8177826

Please sign in to comment.