Skip to content

Commit

Permalink
Handle properly empty if blocks in Style/SafeNavigation (#6993)
Browse files Browse the repository at this point in the history
  • Loading branch information
RicardoTrindade authored and bbatsov committed Apr 30, 2019
1 parent ce27c89 commit 853de37
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

### Bug fixes

* [#6993](https://github.com/rubocop-hq/rubocop/pull/6993): Allowing for empty if blocks, preventing `Style/SafeNavigation` from crashing. ([@RicardoTrindade][])
* [#6995](https://github.com/rubocop-hq/rubocop/pull/6995): Fix an incorrect auto-correct for `Style/RedundantParentheses` when enclosed in parentheses at `while-post` or `until-post`. ([@koic][])
* [#6996](https://github.com/rubocop-hq/rubocop/pull/6996): Fix a false positive for `Style/RedundantFreeze` when freezing the result of `String#*`. ([@bquorning][])
* [#6998](https://github.com/rubocop-hq/rubocop/pull/6998): Fix autocorrect of `Naming/RescuedExceptionsVariableName` to also rename all references to the variable. ([@Darhazer][])
Expand Down Expand Up @@ -3987,3 +3988,4 @@
[@vfonic]: https://github.com/vfonic
[@andreaseger]: https://github.com/andreaseger
[@yakout]: https://github.com/yakout
[@RicardoTrindade]: https://github.com/RicardoTrindade
10 changes: 7 additions & 3 deletions lib/rubocop/cop/style/safe_navigation.rb
Expand Up @@ -72,7 +72,7 @@ class SafeNavigation < Cop

# if format: (if checked_variable body nil)
# unless format: (if checked_variable nil body)
def_node_matcher :modifier_if_safe_navigation_candidate?, <<-PATTERN
def_node_matcher :modifier_if_safe_navigation_candidate, <<-PATTERN
{
(if {
(send $_ {:nil? :!})
Expand Down Expand Up @@ -147,11 +147,15 @@ def extract_parts(node)

def extract_parts_from_if(node)
variable, receiver =
modifier_if_safe_navigation_candidate?(node)
modifier_if_safe_navigation_candidate(node)

checked_variable, matching_receiver, method =
extract_common_parts(receiver, variable)
matching_receiver = nil if LOGIC_JUMP_KEYWORDS.include?(receiver.type)

if receiver && LOGIC_JUMP_KEYWORDS.include?(receiver.type)
matching_receiver = nil
end

[checked_variable, matching_receiver, receiver, method]
end

Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/style/safe_navigation_spec.rb
Expand Up @@ -144,6 +144,15 @@
RUBY
end

it 'allows for empty if blocks with comments' do
expect_no_offenses(<<-RUBY.strip_indent)
if foo
# a random commnet
# TODO: Implement this before
end
RUBY
end

it 'allows a method call as a parameter when the parameter is ' \
'safe guarded with an object check' do
expect_no_offenses('foo(bar.baz) if bar')
Expand Down

0 comments on commit 853de37

Please sign in to comment.