Skip to content

Commit cf897f3

Browse files
authored
Merge pull request #1562 from koic/fix_incorrect_autocorrect_for_rails_redirect_back_or_to_cop
[Fix #1561] Fix incorrect autocorrect for `Rails/RedirectBackOrTo`
2 parents e9daa98 + 768096c commit cf897f3

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1561](https://github.com/rubocop/rubocop-rails/issues/1561): Fix incorrect autocorrect for `Rails/RedirectBackOrTo` when `fallback_location` argument is a hash and the call has no argument parentheses. ([@koic][])

lib/rubocop/cop/rails/redirect_back_or_to.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ def correct_redirect_back(corrector, node, fallback_pair, fallback_value, option
6161
first_pair = hash_arg.pairs.find { |pair| pair != fallback_pair }
6262
corrector.insert_before(first_pair, "#{fallback_value.source}, ")
6363
end
64+
65+
wrap_with_parentheses(node, corrector) unless node.parenthesized?
6466
end
6567
# rubocop:enable Metrics/AbcSize
6668

@@ -77,6 +79,11 @@ def remove_fallback_location_pair(corrector, hash_node, fallback_pair)
7779
end
7880
end
7981

82+
def wrap_with_parentheses(node, corrector)
83+
corrector.replace(node.loc.selector.end.join(node.first_argument.source_range.begin), '(')
84+
corrector.insert_after(node, ')')
85+
end
86+
8087
def remove_first_pair(corrector, fallback_pair, next_pair)
8188
range = fallback_pair.source_range.join(next_pair.source_range.begin)
8289
corrector.remove(range)

spec/rubocop/cop/rails/redirect_back_or_to_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,28 @@
3535
RUBY
3636
end
3737

38+
it 'registers an offense and corrects when `fallback_location` arg is a hash and the call has no arg parentheses' do
39+
expect_offense(<<~RUBY)
40+
redirect_back fallback_location: {action: 'index'}
41+
^^^^^^^^^^^^^ Use `redirect_back_or_to` instead of `redirect_back` with `:fallback_location` keyword argument.
42+
RUBY
43+
44+
expect_correction(<<~RUBY)
45+
redirect_back_or_to({action: 'index'})
46+
RUBY
47+
end
48+
49+
it 'registers an offense and corrects when `fallback_location` arg is a hash and the call uses arg parentheses' do
50+
expect_offense(<<~RUBY)
51+
redirect_back(fallback_location: {action: 'index'})
52+
^^^^^^^^^^^^^ Use `redirect_back_or_to` instead of `redirect_back` with `:fallback_location` keyword argument.
53+
RUBY
54+
55+
expect_correction(<<~RUBY)
56+
redirect_back_or_to({action: 'index'})
57+
RUBY
58+
end
59+
3860
it 'registers no offense when using redirect_back_or_to' do
3961
expect_no_offenses(<<~RUBY)
4062
redirect_back_or_to(root_path)

0 commit comments

Comments
 (0)