diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cdf0322749..cf1b24a9034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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][]) @@ -3985,3 +3986,4 @@ [@vfonic]: https://github.com/vfonic [@andreaseger]: https://github.com/andreaseger [@yakout]: https://github.com/yakout +[@RicardoTrindade]: https://github.com/RicardoTrindade diff --git a/lib/rubocop/cop/style/safe_navigation.rb b/lib/rubocop/cop/style/safe_navigation.rb index 7b8015c41b7..06941b6a705 100644 --- a/lib/rubocop/cop/style/safe_navigation.rb +++ b/lib/rubocop/cop/style/safe_navigation.rb @@ -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? :!}) @@ -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 diff --git a/spec/rubocop/cop/style/safe_navigation_spec.rb b/spec/rubocop/cop/style/safe_navigation_spec.rb index 46968c1ba21..5b1e88cbd40 100644 --- a/spec/rubocop/cop/style/safe_navigation_spec.rb +++ b/spec/rubocop/cop/style/safe_navigation_spec.rb @@ -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')