From 2191f207062ca4fa1fd47ed645acae4b0528a57d Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Wed, 15 Nov 2023 16:14:35 -0600 Subject: [PATCH] Fix word_wrap with empty string Follow-up to #45948. This fixes `word_wrap` to return an empty string instead of `nil` when given an empty string. Fixes #50067. --- actionview/lib/action_view/helpers/text_helper.rb | 2 ++ actionview/test/template/text_helper_test.rb | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index 77445ca2e5..3f81bece25 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -266,6 +266,8 @@ def pluralize(count, singular, plural_arg = nil, plural: plural_arg, locale: I18 # word_wrap('Once upon a time', line_width: 1, break_sequence: "\r\n") # # => Once\r\nupon\r\na\r\ntime def word_wrap(text, line_width: 80, break_sequence: "\n") + return +"" if text.empty? + # Match up to `line_width` characters, followed by one of # (1) non-newline whitespace plus an optional newline # (2) the end of the string, ignoring any trailing newlines diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index 279db5c99b..41bc430c32 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -393,6 +393,11 @@ def test_excerpt_with_separator assert_equal " 1-+1-+ 1-+1", word_wrap(input, line_width: 3, break_sequence: "-+") end + test "word_wrap when no wrapping is necessary" do + assert_equal "1", word_wrap("1", line_width: 3) + assert_equal "", word_wrap("", line_width: 3) + end + def test_pluralization assert_equal("1 count", pluralize(1, "count")) assert_equal("2 counts", pluralize(2, "count"))