Skip to content

Commit

Permalink
[Fix rubocop#13319] Handle literal forward slashes inside a regexp
Browse files Browse the repository at this point in the history
…in `Lint/LiteralInInterpolation`.
  • Loading branch information
dvandersluis committed Oct 11, 2024
1 parent 8c2bdb5 commit 2b19821
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13319](https://github.com/rubocop/rubocop/issues/13319): Handle literal forward slashes inside a `regexp` in `Lint/LiteralInInterpolation`. ([@dvandersluis][])
11 changes: 11 additions & 0 deletions lib/rubocop/cop/lint/literal_in_interpolation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ def on_interpolation(begin_node)
# interpolation should not be removed if the expanded value
# contains a space character.
expanded_value = autocorrected_value(final_node)

if begin_node.parent.regexp_type?
expanded_value = handle_special_regexp_chars(expanded_value)
end

return if in_array_percent_literal?(begin_node) && /\s|\A\z/.match?(expanded_value)

add_offense(final_node) do |corrector|
Expand Down Expand Up @@ -77,6 +82,12 @@ def autocorrected_value(node)
end
# rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity

def handle_special_regexp_chars(value)
return value unless value['/']

value.gsub!('/', '\/')
end

def autocorrected_value_for_string(node)
if node.source.start_with?("'", '%q')
node.children.last.inspect[1..-2]
Expand Down
39 changes: 39 additions & 0 deletions spec/rubocop/cop/lint/literal_in_interpolation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -423,4 +423,43 @@
RUBY
end
end

context 'handling regexp special characters' do
context 'when inside a `regexp` node' do
it 'properly escapes the autocorrection' do
expect_offense(<<~'RUBY')
/test#{'/'}test/
^^^ Literal interpolation detected.
RUBY

expect_correction(<<~'RUBY')
/test\/test/
RUBY
end

it 'handles longer strings' do
expect_offense(<<~'RUBY')
/test#{'/a/b/c/'}test/
^^^^^^^^^ Literal interpolation detected.
RUBY

expect_correction(<<~'RUBY')
/test\/a\/b\/c\/test/
RUBY
end
end

context 'when inside a non-`regexp` node' do
it 'does not escape the autocorrection' do
expect_offense(<<~'RUBY')
"test#{'/'}test"
^^^ Literal interpolation detected.
RUBY

expect_correction(<<~RUBY)
"test/test"
RUBY
end
end
end
end

0 comments on commit 2b19821

Please sign in to comment.