From 7d9a45f33acc0bb75ecdecdb493e90507622da2f Mon Sep 17 00:00:00 2001 From: Anton Khorev Date: Sat, 31 May 2025 18:42:04 +0300 Subject: [PATCH] Truncate rich text descriptions at word boundaries if not too short --- lib/rich_text.rb | 9 ++++++++- test/lib/rich_text_test.rb | 23 +++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/rich_text.rb b/lib/rich_text.rb index 7968e166b..e40289531 100644 --- a/lib/rich_text.rb +++ b/lib/rich_text.rb @@ -6,6 +6,7 @@ module RichText ].freeze DESCRIPTION_MAX_LENGTH = 500 + DESCRIPTION_WORD_BREAK_THRESHOLD_LENGTH = 450 def self.new(format, text) case format @@ -238,7 +239,13 @@ module RichText return nil if text.blank? - text.truncate(DESCRIPTION_MAX_LENGTH) + text_truncated_to_word_break = text.truncate(DESCRIPTION_MAX_LENGTH, :separator => " ") + + if text_truncated_to_word_break.length >= DESCRIPTION_WORD_BREAK_THRESHOLD_LENGTH + text_truncated_to_word_break + else + text.truncate(DESCRIPTION_MAX_LENGTH) + end end def image?(element) diff --git a/test/lib/rich_text_test.rb b/test/lib/rich_text_test.rb index fdae9580f..6afedad83 100644 --- a/test/lib/rich_text_test.rb +++ b/test/lib/rich_text_test.rb @@ -462,15 +462,34 @@ class RichTextTest < ActiveSupport::TestCase def test_markdown_description_max_length m = RichText::DESCRIPTION_MAX_LENGTH + o = 3 # "...".length r = RichText.new("markdown", "x" * m) assert_equal "x" * m, r.description r = RichText.new("markdown", "y" * (m + 1)) - assert_equal "#{'y' * (m - 3)}...", r.description + assert_equal "#{'y' * (m - o)}...", r.description r = RichText.new("markdown", "*zzzzzzzzz*z" * ((m + 1) / 10.0).ceil) - assert_equal "#{'z' * (m - 3)}...", r.description + assert_equal "#{'z' * (m - o)}...", r.description + end + + def test_markdown_description_word_break_threshold_length + m = RichText::DESCRIPTION_MAX_LENGTH + t = RichText::DESCRIPTION_WORD_BREAK_THRESHOLD_LENGTH + o = 3 # "...".length + + r = RichText.new("markdown", "#{'x' * (t - o - 1)} #{'y' * (m - (t - o - 1) - 1)}") + assert_equal "#{'x' * (t - o - 1)} #{'y' * (m - (t - o - 1) - 1)}", r.description + + r = RichText.new("markdown", "#{'x' * (t - o - 1)} #{'y' * (m - (t - o - 1))}") + assert_equal "#{'x' * (t - o - 1)} #{'y' * (m - (t - o - 1) - 4)}...", r.description + + r = RichText.new("markdown", "#{'x' * (t - o)} #{'y' * (m - (t - o) - 1)}") + assert_equal "#{'x' * (t - o)} #{'y' * (m - (t - o) - 1)}", r.description + + r = RichText.new("markdown", "#{'x' * (t - o)} #{'y' * (m - (t - o))}") + assert_equal "#{'x' * (t - o)}...", r.description end private -- 2.39.5