Skip to content

Commit

Permalink
[Fix #9973] Fix a false positive for Layout/RescueEnsureAlignment
Browse files Browse the repository at this point in the history
Fixes #9973.

This PR fixes a false positive for `Layout/RescueEnsureAlignment`
when aligned `rescue` keyword and leading dot.
  • Loading branch information
koic authored and bbatsov committed Aug 12, 2021
1 parent b3f6e50 commit 2fd1221
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9973](https://github.com/rubocop/rubocop/issues/9973): Fix a false positive for `Layout/RescueEnsureAlignment` when aligned `rescue` keyword and leading dot. ([@koic][])
20 changes: 20 additions & 0 deletions lib/rubocop/cop/layout/rescue_ensure_alignment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ def alignment_node(node)
ancestor_node = ancestor_node(node)

return ancestor_node if ancestor_node.nil? || ancestor_node.kwbegin_type?
return if ancestor_node.respond_to?(:send_node) &&
aligned_with_line_break_method?(ancestor_node, node)

assignment_node = assignment_node(ancestor_node)
return assignment_node if same_line?(ancestor_node, assignment_node)
Expand All @@ -131,6 +133,24 @@ def ancestor_node(node)
node.each_ancestor(*ANCESTOR_TYPES).first
end

def aligned_with_line_break_method?(ancestor_node, node)
send_node_loc = ancestor_node.send_node.loc
do_keyword_line = ancestor_node.loc.begin.line
rescue_keyword_column = node.loc.keyword.column
selector = send_node_loc.selector

if send_node_loc.respond_to?(:dot) && (dot = send_node_loc.dot) &&
aligned_with_leading_dot?(do_keyword_line, dot, rescue_keyword_column)
return true
end

do_keyword_line == selector.line && rescue_keyword_column == selector.column
end

def aligned_with_leading_dot?(do_keyword_line, dot, rescue_keyword_column)
do_keyword_line == dot.line && rescue_keyword_column == dot.column
end

def assignment_node(node)
assignment_node = node.ancestors.first
return nil unless
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/layout/rescue_ensure_alignment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,28 @@ def foo
RUBY
end

it 'accepts aligned rescue with do-end block that line break with leading dot for method calls' do
expect_no_offenses(<<~RUBY)
[1, 2, 3]
.each do |el|
el.to_s
rescue StandardError => _exception
next
end
RUBY
end

it 'accepts aligned rescue with do-end block that line break with trailing dot for method calls' do
expect_no_offenses(<<~RUBY)
[1, 2, 3].
each do |el|
el.to_s
rescue StandardError => _exception
next
end
RUBY
end

it 'accepts aligned rescue do-end block assigned to local variable' do
expect_no_offenses(<<~RUBY)
result = [1, 2, 3].map do |el|
Expand Down

0 comments on commit 2fd1221

Please sign in to comment.