Skip to content

Commit 783a4bf

Browse files
authored
Merge pull request #14607 from dvandersluis/redundant-format-control-chars
Fix `Style/RedundantFormat` handling control characters like `\n`
2 parents d897804 + 340d557 commit 783a4bf

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#14607](https://github.com/rubocop/rubocop/pull/14607): Fix `Style/RedundantFormat` handling control characters like `\n`. ([@dvandersluis][])

lib/rubocop/cop/style/redundant_format.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ class RedundantFormat < Base
8989

9090
def on_send(node)
9191
format_without_additional_args?(node) do |value|
92-
replacement = value.source
92+
replacement = escape_control_chars(value.source)
9393

9494
add_offense(node, message: message(node, replacement)) do |corrector|
9595
corrector.replace(node, replacement)
@@ -229,7 +229,12 @@ def quote(string, node)
229229
end
230230
end
231231

232-
"#{start_delimiter}#{string}#{end_delimiter}"
232+
"#{start_delimiter}#{escape_control_chars(string)}#{end_delimiter}"
233+
end
234+
235+
# Escape any control characters in the string (eg. `\t` or `\n` become `\\t` or `\\n`)
236+
def escape_control_chars(string)
237+
string.gsub(/\p{Cc}/) { |s| s.dump[1..-2] }
233238
end
234239

235240
def argument_values(arguments)

spec/rubocop/cop/style/redundant_format_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,17 @@
8484
'foo'
8585
RUBY
8686
end
87+
88+
it 'registers an offense when the argument is a control character' do
89+
expect_offense(<<~'RUBY', method: method)
90+
%{method}("\n")
91+
^{method}^^^^^^ Use `"\n"` directly instead of `%{method}`.
92+
RUBY
93+
94+
expect_correction(<<~'RUBY')
95+
"\n"
96+
RUBY
97+
end
8798
end
8899

89100
context 'with literal arguments' do
@@ -453,6 +464,19 @@
453464
RUBY
454465
end
455466
end
467+
468+
context 'when the string contains control characters' do
469+
it 'registers an offense with the correct message' do
470+
expect_offense(<<~'RUBY', method: method)
471+
%{method}("%s\a\b\t\n\v\f\r\e", 'foo')
472+
^{method}^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `"foo\a\b\t\n\v\f\r\e"` directly instead of `%{method}`.
473+
RUBY
474+
475+
expect_correction(<<~'RUBY')
476+
"foo\a\b\t\n\v\f\r\e"
477+
RUBY
478+
end
479+
end
456480
end
457481
end
458482
end

0 commit comments

Comments
 (0)