Skip to content

Commit

Permalink
Merge pull request #474 from koic/fix_false_negative_for_rails_safe_n…
Browse files Browse the repository at this point in the history
…avigation

Fix a false negative for `Rails/SafeNavigation`
  • Loading branch information
koic authored May 3, 2021
2 parents adff619 + aa69d69 commit f0e8893
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
* [#466](https://github.com/rubocop/rubocop-rails/pull/466): Fix a false positive for `Rails/DynamicFindBy` when not inheriting `ApplicationRecord` and without no receiver. ([@koic][])
* [#147](https://github.com/rubocop/rubocop-rails/issues/147): Fix a false positive for `Rails/HasManyOrHasOneDependent` when specifying default `dependent: nil` strategy. ([@koic][])
* [#137](https://github.com/rubocop/rubocop-rails/issues/137): Make `Rails/HasManyOrHasOneDependent` aware of `readonly?` is `true`. ([@koic][])
* [#474](https://github.com/rubocop/rubocop-rails/pull/474): Fix a false negative for `Rails/SafeNavigation` when using `try!` without receiver. ([@koic][])

### Changes

Expand Down
9 changes: 7 additions & 2 deletions lib/rubocop/cop/rails/safe_navigation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class SafeNavigation < Base
RESTRICT_ON_SEND = %i[try try!].freeze

def_node_matcher :try_call, <<~PATTERN
(send !nil? ${:try :try!} $_ ...)
(send _ ${:try :try!} $_ ...)
PATTERN

def on_send(node)
Expand All @@ -64,7 +64,12 @@ def autocorrect(corrector, node)
method_node, *params = *node.arguments
method = method_node.source[1..-1]

range = range_between(node.loc.dot.begin_pos, node.loc.expression.end_pos)
range = if node.receiver
range_between(node.loc.dot.begin_pos, node.loc.expression.end_pos)
else
corrector.insert_before(node, 'self')
node
end

corrector.replace(range, replacement(method, params))
end
Expand Down
6 changes: 2 additions & 4 deletions spec/rubocop/cop/rails/safe_navigation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@
it_behaves_like 'accepts', 'try! with a method stored as a variable',
['bar = :==',
'foo.try!(baz, bar)'].join("\n")

it 'accepts usages of try! without receiver' do
expect_no_offenses('try!(:something)')
end
end

context 'try' do
Expand Down Expand Up @@ -118,6 +114,8 @@
'[1, 2].try!(:join, ",")', '[1, 2]&.join(",")'
it_behaves_like 'autocorrect', 'try! with multiple parameters',
'[1, 2].try!(:join, bar, baz)', '[1, 2]&.join(bar, baz)'
it_behaves_like 'autocorrect', 'try! without receiver',
'try!(:join)', 'self&.join'
it_behaves_like 'autocorrect', 'try! with a block',
['[foo, bar].try!(:map) do |e|',
' e.some_method',
Expand Down

0 comments on commit f0e8893

Please sign in to comment.