From fe554a3daf74d52f4b3f3d2cdb352ad0495049cc Mon Sep 17 00:00:00 2001 From: Max Chernyak Date: Sun, 4 Sep 2022 13:44:00 -0400 Subject: [PATCH] Chomp the break_sequence in word_wrap When word_wrap's break_sequence contains non-rstrippable characters, word_wrap fails to strip the extra break_sequence at the end properly. Using chomp! helps cut exactly what was specified in the argument. --- actionview/CHANGELOG.md | 32 +++++++++++++++++++ .../lib/action_view/helpers/text_helper.rb | 2 +- actionview/test/template/text_helper_test.rb | 4 +++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index db720888ed..a58f494ba4 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,35 @@ +* Strip `break_sequence` at the end of `word_wrap`. + + This fixes a bug where `word_wrap` didn't properly strip off break sequences that had printable characters. + + For example, compare the outputs of this template: + + ```erb + # <%= word_wrap("11 22\n33 44", line_width: 2, break_sequence: "\n# ") %> + ``` + + Before: + + ``` + # 11 + # 22 + # + # 33 + # 44 + # + ``` + + After: + + ``` + # 11 + # 22 + # 33 + # 44 + ``` + + *Max Chernyak* + * Allow templates to set strict `locals`. By default, templates will accept any `locals` as keyword arguments. To define what `locals` a template accepts, add a `locals` magic comment: diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index 649d00e4f7..63689b4702 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -263,7 +263,7 @@ module ActionView # # => Once\r\nupon\r\na\r\ntime def word_wrap(text, line_width: 80, break_sequence: "\n") text.split("\n").collect! do |line| - line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").rstrip : line + line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").chomp!(break_sequence) : line end * break_sequence end diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index dd89af7fed..46c47ad327 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -376,6 +376,10 @@ class TextHelperTest < ActionView::TestCase assert_equal("1234567890\r\n1234567890\r\n1234567890", word_wrap("1234567890 " * 3, line_width: 2, break_sequence: "\r\n")) end + def test_word_wrap_with_non_strippable_break_sequence + assert_equal("11\n# 22\n# 33", word_wrap("11 22 33", line_width: 2, break_sequence: "\n# ")) + end + def test_pluralization assert_equal("1 count", pluralize(1, "count")) assert_equal("2 counts", pluralize(2, "count"))